二維碼檢測-ZXing

接口部分

@interface ZXingDetector : NSObject

//檢測本地圖片的方法
-(NSArray *)detectCodeWithImage:(UIImage *)image;

//異步檢測本地圖片的方法
-(void)detectCodeWithImage:(UIImage *)image completion:(void (^ __nullable)(NSArray *array))completion;

@end

實現(xiàn)部分

@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);
        });

    });
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容