1.系统自带#import <CoreImage/CoreImage.h>框架生成二维码
/**
* 根据字符串生成二维码 CIImage 对象
*
* @param urlString 需要生成二维码的字符串
*
* @return 生成的二维码
*/
- (CIImage *)creatQRcodeWithUrlstring:(NSString *)urlString{
// 1.实例化二维码滤镜
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 2.恢复滤镜的默认属性 (因为滤镜有可能保存上一次的属性)
[filter setDefaults];
// 3.将字符串转换成NSdata
NSData *data = [urlString dataUsingEncoding:NSUTF8StringEncoding];
// 4.通过KVO设置滤镜, 传入data, 将来滤镜就知道要通过传入的数据生成二维码
[filter setValue:data forKey:@"inputMessage"];
// 5.生成二维码
CIImage *outputImage = [filter outputImage];
return outputImage;
}
系统自带识别图片中的二维码
/**
* 读取图片中的二维码
*
* @param image 图片
*
* @return 图片中的二维码数据集合 CIQRCodeFeature对象
*/
+ (NSArray *)readQRCodeFromImage:(UIImage *)image{
// 创建一个CIImage对象
CIImage *ciImage = [[CIImage alloc] initWithCGImage:image.CGImage options:nil];
CIContext *context = [CIContext contextWithOptions:@{kCIContextUseSoftwareRenderer : @(YES)}]; // 软件渲染
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:@{CIDetectorAccuracy : CIDetectorAccuracyHigh}];// 二维码识别
// 注意这里的CIDetectorTypeQRCode
NSArray *features = [detector featuresInImage:ciImage];
NSLog(@"features = %@",features); // 识别后的结果集
for (CIQRCodeFeature *feature in features) {
NSLog(@"msg = %@",feature.messageString); // 打印二维码中的信息
}
return features;
}
2.ZXing生成二维码。需要导入第三方#import "ZXingObjC.h"
/**
* 根据字符串生成二维码 UIImage 对象
*
* @param str 需要生成二维码的字符串
* @param size 生成的大小
* @param format 二维码选 kBarcodeFormatQRCode
* @return 生成的二维码
*/
+ (UIImage*)createCodeWithString:(NSString*)str
size:(CGSize)size
CodeFomart:(ZXBarcodeFormat)format
{
ZXMultiFormatWriter *writer = [[ZXMultiFormatWriter alloc] init];
ZXBitMatrix *result = [writer encode:str format:format width:size.width height:size.width error:nil];
ZXImage *image = [ZXImage imageWithMatrix:result];
return [UIImage imageWithCGImage:image.cgimage];
}
ZXing识别图片中的二维码
CGImageRef imageRef = image.CGImage;
ZXCGImageLuminanceSource * source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:imageRef];
ZXBinaryBitmap * bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];
NSError * error = nil;
ZXDecodeHints * hints = [ZXDecodeHints hints];
ZXMultiFormatReader * reader = [ZXMultiFormatReader reader];
ZXResult * result = [reader decode:bitmap hints:hints error:&error];
if (result) {
NSString * contents = result.text;
}