CIImage与二维码图片生成

代码:

#import "ViewController.h"
#import <CoreImage/CoreImage.h>

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIImage *qrImage =  [self qrCodeImageForString:@"http://www.baidu.com" sideLength:300];
    // code...
}

/**
 * 根据字符串生成二维码图片
 *
 * @param string 字符串
 * @param sizeLength 二维码图片的边长
 * @return 二维码图片
 */
- (UIImage *)qrCodeImageForString:(NSString *)string sideLength:(CGFloat)sizeLength {
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [qrFilter setDefaults];
    [qrFilter setValue:[string dataUsingEncoding:NSUTF8StringEncoding] forKey:@"inputMessage"];
    CIImage *outputCiImage = qrFilter.outputImage;
    UIImage *qrImage = [self createNonInterpolatedUIImageFormCIImage:outputCiImage sideLength:sizeLength];
    return qrImage;
}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image sideLength:(CGFloat)sizeLength {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(sizeLength / CGRectGetWidth(extent), sizeLength / CGRectGetHeight(extent));
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(NULL, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

 

转载于:https://www.cnblogs.com/xwoder/p/6216064.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值