Tuesday, 17 September 2013

Cropping an image taken from AVCaptureStillImageOutput

Cropping an image taken from AVCaptureStillImageOutput

I am trying to crop an image taken from AVCaptureStillImageOutput but
unable to properly crop at the correct rectangles.
My preview of camera video is 320x458 frame and the cropping rectangle is
present inside this preview frame which has the co-ordinates and size as
CGRectMake(60, 20, 200, 420).
After taking the picture, I receive the image from
NSData *imageData = [AVCaptureStillImageOutput
jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [[UIImage alloc] initWithData:imageData];
UIImage *finalImage = [self cropImage:image];
Afterwards I am trying to crop this actual image of size 1080x1920 with
the below function. I am getting a wayward clipping and the resultant
image is way out of the actual rectangle! ;(
- (UIImage *)cropImage:(UIImage *)oldImage {
CGRect rect = CGRectMake(60, 20, 200, 420);
CGSize boundSize = CGSizeMake(320, 458);
float widthFactor = rect.size.width *
(oldImage.size.width/boundSize.width);
float heightFactor = rect.size.height *
(oldImage.size.height/boundSize.height);
float factorX = rect.origin.x * (oldImage.size.width/boundSize.width);
float factorY = rect.origin.y * (oldImage.size.height/boundSize.height);
CGRect factoredRect =
CGRectMake(factorX,factorY,widthFactor,heightFactor);
UIImage *croppedImage = [UIImage
imageWithCGImage:CGImageCreateWithImageInRect([oldImage CGImage],
factoredRect) scale:oldImage.scale
orientation:oldImage.imageOrientation];
return croppedImage;
}
In the attached picture, I am trying to crop the coffee mug, but what I
get is not the correct cropped image!

No comments:

Post a Comment