1. 程式人生 > >iOS 掃描相簿圖片二維碼

iOS 掃描相簿圖片二維碼

級別:★★☆☆☆
標籤:「iOS CIDetector」「CIQRCodeFeature」「識別相簿圖片」
作者: Xs·H
審校: QiShare團隊


接上篇 iOS 掃描二維碼/條形碼,本文補充介紹掃描相簿圖片上二維碼的實現方式。先看看QiQRCode中的示例效果:

iOS 掃描相簿圖片上二維碼效果

iOS 8之後,可以結合CIDetector使用CIQRCodeFeature實現掃描相簿圖片上二維碼的功能。具體實現過程如下:

1、遵守協議
@interface QiCodeManager () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
複製程式碼
2、開啟相簿
- (void)presentPhotoLibraryWithRooter:(UIViewController *)rooter callback:(nonnull void (^)(NSString * _Nonnull))callback {
    _callback = callback;
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // imagePicker.allowsEditing = YES;
    imagePicker.delegate = self;
    [rooter presentViewController:imagePicker animated:YES completion:nil];
}
複製程式碼
3、實現代理
// UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    
    UIImage *pickedImage = info[UIImagePickerControllerEditedImage] ?: info[UIImagePickerControllerOriginalImage];
    CIImage *detectImage = [CIImage imageWithData:UIImagePNGRepresentation(pickedImage)];
    
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
    CIQRCodeFeature *feature = (CIQRCodeFeature *)[detector featuresInImage:detectImage options:nil].firstObject;
    
    [picker dismissViewControllerAnimated:YES completion:^{
        if (feature.messageString) {
            [self handleCodeString:feature.messageString];
        }
    }];
}
複製程式碼
4、透傳給業務
- (void)handleCodeString:(NSString *)codeString {
    
    if (_autoStop) {
        [self stopScanning];
    }
    if (_callback) {
        _callback(codeString);
    }
}
複製程式碼
5、業務呼叫方式
// 建立“相簿”按鈕
UIBarButtonItem *photoItem = [[UIBarButtonItem alloc] initWithTitle:@"相簿" style:UIBarButtonItemStylePlain target:self action:@selector(photo:)];

self.navigationItem.rightBarButtonItem = photoItem;
複製程式碼
// 實現“相簿”按鈕方法
- (void)photo:(id)sender {
    
    __weak typeof(self) weakSelf = self;
    [_codeManager presentPhotoLibraryWithRooter:self callback:^(NSString * _Nonnull code) {
        [weakSelf performSegueWithIdentifier:@"showCodeGeneration" sender:code];
    }];
}
複製程式碼

上述程式碼中的核心步驟是第3步—實現代理。 我們通過UIImagePickerController拿到image後,使用CIDetectorCIQRCodeFeature讀取image上的資訊,最終得到的feature.messageString就是二維碼的字串資訊。


示例原始碼QiQRCode可從GitHub的QiShare開源庫中獲取。


關注我們的途徑有:
QiShare(簡書)
QiShare(掘金)
QiShare(知乎)
QiShare(GitHub)
QiShare(CocoaChina)
QiShare(StackOverflow)
QiShare(微信公眾號)

推薦文章:
iOS 瞭解Xcode Bitcode
iOS 重繪之drawRect
iOS 編寫高質量Objective-C程式碼(八)
iOS KVC與KVO簡介
奇舞週刊