最近公司碰到一個需求:聊天禁止二維碼辆苔。然后碰到微信的個人名片二維碼有一張識別不出來(個人二維碼有很多樣式的)
識別二維碼?
我是寫的一個UIImage的類目實(shí)現(xiàn)
- (NSString *)qrimageToStr{ CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:nil]; UIImage *image = [self imageCompressForWidth:640]; NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
? ? __block NSString *message = nil;
? ? [features enumerateObjectsUsingBlock:^(CIFeature * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
? ? ? ? if ([obj isKindOfClass:[CIQRCodeFeature class]]) {
? ? ? ? ? ? message = [(CIQRCodeFeature *)obj messageString];
? ? ? ? ? ? *stop=YES;
? ? ? ? }
? ? }];
? ? return message;
}
最開始發(fā)現(xiàn)不能識別二維碼就以為是識別精度問題戏售,然后就設(shè)置了options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}
發(fā)現(xiàn)還是識別不出來冈欢,于是想到下壓縮下圖片試試,沒想到一試就ok了鹰贵。
壓縮圖片
- (UIImage *)imageCompressForWidth:(CGFloat)defineWidth
{
? ? CGSize imageSize = self.size;
? ? CGFloat width = imageSize.width;
? ? CGFloat height = imageSize.height;
? ? CGFloat targetWidth = defineWidth;
? ? NSInteger targetHeight = (targetWidth / width) * height;
? ? UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
? ? [self drawInRect:CGRectMake(0,0,targetWidth,? targetHeight)];
? ? UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
? ? UIGraphicsEndImageContext();
? ? return newImage;
}
識別二維碼時争拐,壓縮圖片會提高精度和效率艘绍。
當(dāng)二維碼識別不出來時可以試試壓縮圖片