一个特别简易的生成二维码的功能
不需要添加任何库
/*
生成二维码图片
codeUrl:链接
image_W:图片宽度
retrun:二维码图片
*/
+(UIImage *)QRCodeGenerate:(NSString*)codeUrl imageWidth:(CGFloat)image_W{
//生成二维码
// 1. 创建一个二维码滤镜实例(CIFilter)
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 滤镜恢复默认设置
[filter setDefaults];
// 2. 给滤镜添加数据
NSData *data = [codeUrl dataUsingEncoding:NSUTF8StringEncoding];
[filter setValue:data forKeyPath:@"inputMessage"];
// 3. 生成高清二维码
CIImage *image = [filter outputImage];
CGRect extent = CGRectIntegral(image.extent);
CGFloat scale = MIN(image_W/CGRectGetWidth(extent), image_W/CGRectGetHeight(extent));
// 1.创建bitmap;
size_t width = CGRectGetWidth(extent) * scale;
size_t height = CGRectGetHeight(extent) * scale;
CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
CGContextRef bitmapRef = CGBitmapContextCreate(nil, 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);
// 2.保存bitmap到图片
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}
附加小功能---
判断图片中是否有二维码图片
+ (BOOL)IsThereQRCode:(UIImage *)codeImage{
CIImage *detectImage = [CIImage imageWithData:UIImagePNGRepresentation(codeImage)];
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
CIQRCodeFeature *feature = (CIQRCodeFeature *)[detector featuresInImage:detectImage options:nil].firstObject;
if (feature.messageString) {
return YES;
}else{
return NO;
}
}
网友评论