過去嘗試過用相機掃描QRCode,現在想要讀取影像中QRCode,可以怎麼做呢?

若有使用心動健康(名字暫定)的朋友,可以加我好友喔:)~
原來只要把UIImage轉成CIImage,CIDetector就能去偵測影像中的QRCode。
/**
Theme: Detect Image from Image
IDE: Xcode 9
Language: Objective C
Date: 106/11/16
Author: HappyMan
Blog: https://cg2010studio.com/
*/
-(NSArray *)detectQRCode:(UIImage *)image
{
@autoreleasepool {
NSLog(@"%@ :: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
NSCAssert(image != nil, @"**Assertion Error** detectQRCode : image is nil");
CIImage *ciImage = [[CIImage alloc] initWithImage:image]; // 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;
}
}
最需要注意的是UIImage目前直接轉為CIImage會回傳nil。
CIImage *ciImage = image.CIImage
要改成下列方式來轉換:
CIImage *ciImage = [[CIImage alloc] initWithImage:image];
小米運動加好友也是能從影像中讀取QRCode呢!
在debug的時候顯示CIImage:
可以看到它在做矩陣運算~

隨意留個言吧:)~