简体   繁体   中英

How to crop image in iPhone?

In my application I m using following codes to crop the captured image :-

-(void)imagePickerController:(UIImagePickerController *) picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{   
#ifdef _DEBUG
    NSLog(@"frmSkinImage-imagePickerController-Start");
#endif

    imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    //=======================================
    UIImage *image =imageView.image;
    CGRect cropRect = CGRectMake(100, 100, 125,128);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
    [imageView setImage:[UIImage imageWithCGImage:imageRef]]; 
    CGImageRelease(imageRef);
    //===================================================
    //imgglobal = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    // for saving image to photo album
    //UIImageWriteToSavedPhotosAlbum(imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), self);
    [picker dismissModalViewControllerAnimated:YES];

#ifdef _DEBUG
    NSLog(@"frmSkinImage-imagePickerController-End");
#endif
}

But my problem is that when I use camera to take photo to crop the captured image it rotates the image to 90 degree towards right and in case I use Photo library it works perfectly.

So can you examine my above code, to see where I am wrong?

The CGImage is a UIImage without the meta data, and therefore loses the orientation information. I'd suggest that you get the orientation of the original [UIImage imageOrientation], store it and then apply it to the final image.

If that doesn't work, try applying a CGAffineTransformMakeRotation(90.0*0.0174532925); to the final image according to the orientation of the original.

Fastest and easiest way is to have a look to NYXImagesKit . With UIImage+Resizing category you can crop image. From the documentation:

UIImage+Resizing

This category can be used to crop or to scale images.

Cropping

You can crop your image by 9 different ways :

Top left Top center Top right Bottom left Bottom center Bottom right Left center Right center Center

UIImage* cropped = [myImage cropToSize:(CGSize){width, height} usingMode:NYXCropModeCenter];

NYXCropMode is an enum type which can be found in the header file, it is used to represent the 9 modes above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM