来自AVCaptureMetadataOutput委托的UIImage(didOutputMetadataObjects)

时间:2014-05-11 17:13:51

标签: ios objective-c uiimage avcapturesession

我正在扫描QR Code&条形码使用AVCaptureMetadataOutput。然后当相机聚焦到条形码didOutputMetadataObjects委托被调用时,我能够获得条形码元数据字符串。但我想知道如何从didOutputMetadataObjects代表处获取扫描图像(条形码图像)。

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
// How to get the scanned image from this delegate ?
}

提前致谢..

1 个答案:

答案 0 :(得分:1)

这将为您提供一个可以随意选择的UIImage。

- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection {
    // You only want this to run after the barcode is captured, so I use a bool value to control entry
    if (_captured) {
        _captured = NO;
        [_session stopRunning];
        CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
        CVPixelBufferLockBaseAddress(imageBuffer,0);
        uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
        size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
        size_t width = CVPixelBufferGetWidth(imageBuffer);
        size_t height = CVPixelBufferGetHeight(imageBuffer);

        // Take the image buffer you have and create a CGImageRef
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
        CGImageRef newImage = CGBitmapContextCreateImage(newContext);
        baseAddress = nil;
        // Clean up
        CGContextRelease(newContext);
        CGColorSpaceRelease(colorSpace);
        // Start with a base image to original scale
        UIImage *imageBase = [UIImage imageWithCGImage:newImage scale:1.0 orientation:UIImageOrientationRight];
        // You can resize image if you want
        UIImage *imageFinal = [UIImage resizeImage:imageBase scaledToSize:CGSizeMake(480.0, 640.0)];
        imageBase = nil;
        CGImageRelease(newImage);
        CVPixelBufferUnlockBaseAddress(imageBuffer,0);
        imageBuffer = nil;
    }
}