Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage from AVCaptureMetadataOutput delegate (didOutputMetadataObjects)

I am scanning QR Code & Barcode using AVCaptureMetadataOutput. When then camera is focused to barcode didOutputMetadataObjects delegate is called and I am able to get barcode metadata string. But I wonder how to get the scanned image(barcode image) from the didOutputMetadataObjects delegate .

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

Thanks in advance..

like image 525
Prashanth Rajagopalan Avatar asked May 11 '14 17:05

Prashanth Rajagopalan


1 Answers

This will get you a UIImage that you can do as you choose with.

- (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;
    }
}
like image 136
CodeBender Avatar answered Nov 10 '22 23:11

CodeBender