二维码检测-ZXing

接口部分

@interface ZXingDetector : NSObject

//检测本地图片的方法
-(NSArray *)detectCodeWithImage:(UIImage *)image;

//异步检测本地图片的方法
-(void)detectCodeWithImage:(UIImage *)image completion:(void (^ __nullable)(NSArray *array))completion;

@end

实现部分

@interface ZXingDetector ()

@property (nonatomic,strong) dispatch_queue_t detectQueue;

@end

@implementation ZXingDetector

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSString *bundleIdentifier = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
        NSString *labelStr = [NSString stringWithFormat:@"%@_camera",bundleIdentifier];
        self.detectQueue = dispatch_queue_create([labelStr cStringUsingEncoding:NSUTF8StringEncoding], NULL);
    }
    return self;
}

//检测本地图片的方法
-(NSArray *)detectCodeWithImage:(UIImage *)image
{
    if (image == nil) {
        return nil;
    }

    ZXLuminanceSource *source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:image.CGImage];
    ZXBinaryBitmap *bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];
    NSError *error = nil;
    // There are a number of hints we can give to the reader, including possible formats, allowed lengths, and the string encoding.
    ZXDecodeHints *hints = [ZXDecodeHints hints];
    ZXMultiFormatReader *reader = [ZXMultiFormatReader reader];
    
    ZXResult *result = [reader decode:bitmap
                                hints:hints
                                error:&error];
    
    NSMutableArray *muArray = [NSMutableArray array];
    if (result) {
      // The coded result as a string. The raw data can be accessed with result.rawBytes and result.length.
      NSString *contents = result.text;
        [muArray addObject:[contents copy]];

      // The barcode format, such as a QR code or UPC-A
      //ZXBarcodeFormat format = result.barcodeFormat;
    } else {
      // Use error to determine why we didn't get a result, such as a barcode not being found, an invalid checksum, or a format inconsistency.
    }
    return muArray;
}

-(void)detectCodeWithImage:(UIImage *)image completion:(void (^ __nullable)(NSArray *array))completion
{
    dispatch_async(self.detectQueue, ^{
        NSArray *array = [self detectCodeWithImage:image];
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(array);
        });

    });
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

推荐阅读更多精彩内容