How to crop an image from AVCapture to a rect seen on the display

后端 未结 4 1375
梦谈多话
梦谈多话 2021-01-30 08:59

This is driving me crazy because I can\'t get it to work. I have the following scenario:

I\'m using an AVCaptureSession and an AVCaptureVideoPreviewLa

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-30 09:34

    I've solved this problem by using metadataOutputRectOfInterestForRect function.

    It works with any orientation.

    [_stillImageOutput captureStillImageAsynchronouslyFromConnection:stillImageConnection
                                                   completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
     {
         if (error)
         {
             [_delegate cameraView:self error:@"Take picture failed"];
         }
         else
         {
    
             NSData *jpegData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
             UIImage *takenImage = [UIImage imageWithData:jpegData];
    
             CGRect outputRect = [_previewLayer metadataOutputRectOfInterestForRect:_previewLayer.bounds];
             CGImageRef takenCGImage = takenImage.CGImage;
             size_t width = CGImageGetWidth(takenCGImage);
             size_t height = CGImageGetHeight(takenCGImage);
             CGRect cropRect = CGRectMake(outputRect.origin.x * width, outputRect.origin.y * height, outputRect.size.width * width, outputRect.size.height * height);
    
             CGImageRef cropCGImage = CGImageCreateWithImageInRect(takenCGImage, cropRect);
             takenImage = [UIImage imageWithCGImage:cropCGImage scale:1 orientation:takenImage.imageOrientation];
             CGImageRelease(cropCGImage);
    
         }
     }
     ];
    

    The takenImage is still imageOrientation dependent image. You can delete orientation information for further image processing.

    UIGraphicsBeginImageContext(takenImage.size);
    [takenImage drawAtPoint:CGPointZero];
    takenImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

提交回复
热议问题