Skip to content

Instantly share code, notes, and snippets.

@shexbeer
Last active August 31, 2018 17:00
Show Gist options
  • Save shexbeer/cb069d36ca8ec5edb515 to your computer and use it in GitHub Desktop.
Save shexbeer/cb069d36ca8ec5edb515 to your computer and use it in GitHub Desktop.
Crops a Picture from AVCaptureSession to the bounds of the AVCaptureVideoPreviewLayer (so Preview = CameraImage)
-(UIImage*) cropCameraImage:(UIImage*) original toPreviewLayerBounds:(AVCaptureVideoPreviewLayer*) previewLayer {
UIImage *ret = nil;
CGRect previewImageLayerBounds = previewLayer.bounds;
// This calculates the crop area.
// keeping in mind that this works with on an unrotated image (so a portrait image is actually rotated counterclockwise)
// thats why we use originalHeight to calculate the width
float originalWidth = original.size.width;
float originalHeight = original.size.height;
CGPoint A = previewImageLayerBounds.origin;
CGPoint B = CGPointMake(previewImageLayerBounds.size.width, previewImageLayerBounds.origin.y);
// CGPoint C = CGPointMake(self.imageViewTop.bounds.origin.x, self.imageViewTop.bounds.size.height);
CGPoint D = CGPointMake(previewImageLayerBounds.size.width, previewImageLayerBounds.size.height);
CGPoint a = [previewLayer captureDevicePointOfInterestForPoint:A];
CGPoint b = [previewLayer captureDevicePointOfInterestForPoint:B];
// CGPoint c = [previewLayer captureDevicePointOfInterestForPoint:C];
CGPoint d =[previewLayer captureDevicePointOfInterestForPoint:D];
float posX = floor(b.x * originalHeight);
float posY = floor(b.y * originalWidth);
CGFloat width = d.x * originalHeight - b.x * originalHeight;
CGFloat height = a.y * originalWidth - b.y * originalWidth;
CGRect cropRectangle = CGRectMake(posX, posY, width, height);
// This performs the image cropping.
CGImageRef imageRef = CGImageCreateWithImageInRect([original CGImage], cropRectangle);
ret = [UIImage imageWithCGImage:imageRef
scale:original.scale
orientation:original.imageOrientation];
CGImageRelease(imageRef);
return ret;
}
@shexbeer
Copy link
Author

Example call:

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
 // *** some code ***

UIImage *croppedImage = [self cropCameraImage:cameraImage toPreviewLayerBounds:_captureVideoPreviewLayer];
}

@erwinl
Copy link

erwinl commented Feb 13, 2015

Thank you

@iwazer
Copy link

iwazer commented Dec 7, 2015

This snippet was really helpful . Thank you.

@eddieespinal
Copy link

Here is a swift version that I created based on this one:
[https://gist.github.com/eddieespinal/a7bb8a97ac3e935af1fb]

Thanks @shexbeer, this helped me a lot too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment