iOS 掃描相冊圖片二維碼

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


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

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

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

一、遵照協議
@interface QiCodeManager () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
複製代碼
二、打開相冊
- (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];
}
複製代碼
三、實現代理
// 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];
        }
    }];
}
複製代碼
四、透傳給業務
- (void)handleCodeString:(NSString *)codeString {
    
    if (_autoStop) {
        [self stopScanning];
    }
    if (_callback) {
        _callback(codeString);
    }
}
複製代碼
五、業務調用方式
// 建立「相冊」按鈕
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開源庫中獲取。spa


做者微信: 3d

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

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

相關文章
相關標籤/搜索