我知道您可以使用AVFoundation使用设备的相机扫描QR码.现在问题来了,如何从静态UI
Image对象中执行此操作?
解决方法
iOS API提供CoreImage框架中的CIDetector类.
CIDetector可让您在图像中找到特定的图案,如面部,微笑,眼睛,或者在我们的案例中:QRCodes.
CIDetector可让您在图像中找到特定的图案,如面部,微笑,眼睛,或者在我们的案例中:QRCodes.
以下是在Objective-C中从UIImage检测QRCode的代码:
-(NSArray *)detectQRCode:(UIImage *) image { @autoreleasepool { NSLog(@"%@ :: %@",NSStringFromClass([self class]),NSStringFromSelector(_cmd)); NSCAssert(image != nil,@"**Assertion Error** detectQRCode : image is nil"); CIImage* ciImage = UIImage.CIImage; // assuming underlying data is a CIImage //CIImage* ciImage = [CIImage initWithCGImage: UIImage.CGImage]; // to use if the underlying data is a CGImage NSDictionary* options; CIContext* context = [CIContext context]; options = @{ CIDetectorAccuracy : CIDetectorAccuracyHigh }; // Slow but thorough //options = @{ CIDetectorAccuracy : CIDetectorAccuracyLow}; // Fast but superficial CIDetector* qrDetector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:options]; if ([[ciImage properties] valueForKey:(NSString*) kCGImagePropertyOrientation] == nil) { options = @{ CIDetectorImageOrientation : @1}; } else { options = @{ CIDetectorImageOrientation : [[ciImage properties] valueForKey:(NSString*) kCGImagePropertyOrientation]}; } NSArray * features = [qrDetector featuresInImage:ciImage options:options]; return features; } }
如果存在并检测到QRCode,则返回的NSArray *将包含CIFeature *.如果没有QRCode,NSArray *将为零.如果QRCode解码失败,NSArray *将没有元素.
要获取编码的字符串:
if (features != nil && features.count > 0) { for (CIQRCodeFeature* qrFeature in features) { NSLog(@"QRFeature.messageString : %@ ",qrFeature.messageString); } }
在@ Duncan-C的答案中,您可以提取QRCode角并在图像上绘制QRCode的封闭边界框.
注意 :
在iOS10.0 beta 6下,当使用来自cameraSampleBuffer的图像时,调用[qrDetector featuresInImage:ciImage选项:选项]会记录此内部警告(它运行顺利但是垃圾邮件控制台带有此消息,我找不到办法现在摆脱它):
Finalizing CVPixelBuffer 0x170133e20 while lock count is 1.
资源 :