Date
Oct. 7th, 2024
 
2024年 9月 5日

Post: iOS : 二维码扫描之图片识别

Today is the A Memorial Day

iOS : 二维码扫描之图片识别

Published 12:02 Feb 12, 2015.

Created by @ezra. Categorized in #Programming, and tagged as #iOS.

Source format: Markdown

Table of Content

上文,好久之前试了试二维码扫描功能,由于苹果实现了基本的检测,我们要做的其实就只是实现一个摄像机功能。最近公司项目需要从图片识别二维码,于是趁这个机会把新的代码贴上来,正如我所说,依然不需要什么智商。

#pragma mark - 打开相册
- (void)openPhotoAlbum {
    PSImagePickerViewController *picker = [[PSImagePickerViewController alloc] init];
    [picker setShowUpperLimit:NSIntegerMax];
    [picker setSelectUpperLimit:1];
    [picker setDelegate:self];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:picker];
    [self showDetailViewController:nav sender:self];
}

#pragma mark - 从图片读取二维码
- (NSArray <NSString *>*)QRCodeScanFromImage:(UIImage *)image {
    NSMutableArray *results = [NSMutableArray array];
    if (image == nil) {
        return results;
    }
    CIImage *ciImage = [CIImage imageWithCGImage:image.CGImage];
    CIContext *context = [CIContext contextWithOptions:@{kCIContextUseSoftwareRenderer: @(YES)}];
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode
                                              context:context
                                              options:@{CIDetectorAccuracy: CIDetectorAccuracyHigh}];
    NSArray *features = [detector featuresInImage:ciImage];
    if (features == nil || !features.count) {
        return results;
    }
    for (CIQRCodeFeature *feature in features) {
        [results addObject:feature.messageString];
    }
    return results;
}

#pragma mark - 相册选择照片代理方法
- (void)imagePicker:(PSImagePickerViewController *)imagePicker didSelectImages:(NSArray *)images {
    if (images != nil && images.count) {
        NSArray *results = [self QRCodeScanFromImage:[images firstObject]];
        if (results.count) {
            for (NSString *string in results) {
                NSLog(@"\nAlbum QRCode: %@", string);
                // 自定义校验扫描结果的方法
                if ([string containsCouponString]) {
                    if (self.scannerCallBackBlock) {
                        self.scannerCallBackBlock([string couponStringIfContains]);
                    }
                    [self backViewController];
                    break;
                }
            }
        }
        [self noQRCodeCaptured];
    }
}

#pragma mark - 没有捕获到有效二维码或格式不符的提示
- (void)noQRCodeCaptured {
    [self.view makeToast:@"no_qrcode_captured"];
}

看吧,我会乱说?

Pinned Message
HOTODOGO
The Founder and CEO of Infeca Technology.
Developer, Designer, Blogger.
Big fan of Apple, Love of colour.
Feel free to contact me.
反曲点科技创始人和首席执行官。
开发、设计与写作皆为所长。
热爱苹果、钟情色彩。
随时恭候 垂询