美文网首页
二维码检测-ZXing

二维码检测-ZXing

作者: 和女神经常玩 | 来源:发表于2022-12-31 00:05 被阅读0次

    接口部分

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

    相关文章

      网友评论

          本文标题:二维码检测-ZXing

          本文链接:https://www.haomeiwen.com/subject/ctqfcdtx.html