Last active
August 31, 2018 17:00
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(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; | |
} |
Thank you
This snippet was really helpful . Thank you.
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
Example call: