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];
}

 

posted @ 2016-12-23 20:33  Xwoder  阅读(213)  评论(0编辑  收藏  举报