Cropping an UIImage

crop uiimage objective-c
ios crop image example
swiftui crop image
crop ciimage
cgimagecreatewithimageinrect
swift 4 crop image github
uiimage resize
uiimagepickercontroller crop image

I've got some code that resizes an image so I can get a scaled chunk of the center of the image - I use this to take a UIImage and return a small, square representation of an image, similar to what's seen in the album view of the Photos app. (I know I could use a UIImageView and adjust the crop mode to achieve the same results, but these images are sometimes displayed in UIWebViews).

I've started to notice some crashes in this code and I'm a bit stumped. I've got two different theories and I'm wondering if either is on-base.

Theory 1) I achieve the cropping by drawing into an offscreen image context of my target size. Since I want the center portion of the image, I set the CGRect argument passed to drawInRect to something that's larger than the bounds of my image context. I was hoping this was Kosher, but am I instead attempting to draw over other memory that I shouldn't be touching?

Theory 2) I'm doing all of this in a background thread. I know there are portions of UIKit that are restricted to the main thread. I was assuming / hoping that drawing to an offscreen view wasn't one of these. Am I wrong?

(Oh, how I miss NSImage's drawInRect:fromRect:operation:fraction: method.)

Update 2014-05-28: I wrote this when iOS 3 or so was the hot new thing, I'm certain there are better ways to do this by now, possibly built-in. As many people have mentioned, this method doesn't take rotation into account; read some additional answers and spread some upvote love around to keep the responses to this question helpful for everyone.

Original response:

I'm going to copy/paste my response to the same question elsewhere:

There isn't a simple class method to do this, but there is a function that you can use to get the desired results: CGImageCreateWithImageInRect(CGImageRef, CGRect) will help you out.

Here's a short example using it:

CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);
// or use the UIImage wherever you like
[UIImageView setImage:[UIImage imageWithCGImage:imageRef]]; 
CGImageRelease(imageRef);

cropping(to:), Cropping removes content around the designated rectangle; it cuts out the cgImage?.cropping(to:cropZone) else { return nil } // Return image to UIImage let​  One library drew our attention though: TOCropViewController, a UIIMage cropping project made by Tim Oliver, allowing users to crop and rotate UIImage with an iOS look and feel. The only problem being: it is an Objective-C library.

To crop retina images while keeping the same scale and orientation, use the following method in a UIImage category (iOS 4.0 and above):

- (UIImage *)crop:(CGRect)rect {
    if (self.scale > 1.0f) {
        rect = CGRectMake(rect.origin.x * self.scale,
                          rect.origin.y * self.scale,
                          rect.size.width * self.scale,
                          rect.size.height * self.scale);
    }

    CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

Cropping Images in Swift and the Basics of UIImage, CGImage and , When I started searching for the ways to crop image in Swift, I was confused by the difference between UIImage, CGImage, and CIImage. Extension for cropping an UIImage to a square. GitHub Gist: instantly share code, notes, and snippets.

You can make a UIImage category and use it wherever you need. Based on HitScans response and comments bellow it.

@implementation UIImage (Crop)

- (UIImage *)crop:(CGRect)rect {

    rect = CGRectMake(rect.origin.x*self.scale, 
                      rect.origin.y*self.scale, 
                      rect.size.width*self.scale, 
                      rect.size.height*self.scale);       

    CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef 
                                          scale:self.scale 
                                    orientation:self.imageOrientation]; 
    CGImageRelease(imageRef);
    return result;
}

@end

You can use it this way:

UIImage *imageToCrop = <yourImageToCrop>;
CGRect cropRect = <areaYouWantToCrop>;   

//for example
//CGRectMake(0, 40, 320, 100);

UIImage *croppedImage = [imageToCrop crop:cropRect];

iOS: Crop a UIImage to the specified Rect · GitHub, private func CropImage( image:UIImage , cropRect:CGRect) -> UIImage { UIGraphicsBeginImageContextWithOptions(cropRect.size, false, 0); let context  The cropping seems to work but I can't get it to crop the section of the image that I actually want. For example, arguments (50,50,500,500) returns a portion of the image from the top right of the screen, which makes no sense to me.

Swift 3 version
func cropImage(imageToCrop:UIImage, toRect rect:CGRect) -> UIImage{

    let imageRef:CGImage = imageToCrop.cgImage!.cropping(to: rect)!
    let cropped:UIImage = UIImage(cgImage:imageRef)
    return cropped
}


let imageTop:UIImage  = UIImage(named:"one.jpg")! // add validation

with help of this bridge function CGRectMake -> CGRect (credits to this answer answered by @rob mayoff):

 func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {
    return CGRect(x: x, y: y, width: width, height: height)
}

The usage is:

if var image:UIImage  = UIImage(named:"one.jpg"){
   let  croppedImage = cropImage(imageToCrop: image, toRect: CGRectMake(
        image.size.width/4,
        0,
        image.size.width/2,
        image.size.height)
    )
}

Output:

MediaKit/UIImage+Crop.swift at master · wonderkiln/MediaKit · GitHub, public extension UIImage {. public func crop(to rect: CGRect, withRotation rotation: CGAffineTransform) -> UIImage {. let rotatedImage  If you are displaying or processing your image primarily as a CGImage or UIImage, with no additional Core Image application, consider cropping in Core Graphics using the cropping(to:) function to save processing overhead from conversion of images to CIImage. It makes most sense to use cropped(to:) when you already have CIImage in your pipeline.

Here is my UIImage crop implementation which obeys the imageOrientation property. All orientations were thoroughly tested.

inline double rad(double deg)
{
    return deg / 180.0 * M_PI;
}

UIImage* UIImageCrop(UIImage* img, CGRect rect)
{
    CGAffineTransform rectTransform;
    switch (img.imageOrientation)
    {
        case UIImageOrientationLeft:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -img.size.height);
            break;
        case UIImageOrientationRight:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -img.size.width, 0);
            break;
        case UIImageOrientationDown:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -img.size.width, -img.size.height);
            break;
        default:
            rectTransform = CGAffineTransformIdentity;
    };
    rectTransform = CGAffineTransformScale(rectTransform, img.scale, img.scale);

    CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], CGRectApplyAffineTransform(rect, rectTransform));
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:img.scale orientation:img.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

Image Crop / Rotate / Resize Handling in iOS, This method will return UIImage object of cropped image. First we will start from creating an image context for drawing environment. Swift. iphone - ratio - UIImage: Resize, then Crop swift resize image keep aspect ratio (11) An older post contains code for a method to resize your UIImage.

How To Crop An Image (UIImage) - Take Two, In this post I'll show another way to crop with a lot less code. The image I'll crop is shown below: UIImage *image =  cropping (to:) performs the following tasks to create the subimage: It calls the integral function to adjust the rect parameter to integral bounds. It intersects the rect with a rectangle whose origin is (0,0) and size is equal to the size of the image specified by It reads the pixels within the

Cropping and Resizing Images from Camera in iOS and Objective-C, This function takes a UIImage and returns a UIImage that is scaled to the specified size and has the correct orientation. - (UIImage *)​squareImageWithImage:(  I am using this to display image which ratio is different from my frame, so I center it and crop the sides. extension UIImage { func cropTo(size: CGSize) -> UIImage { guard let cgimage = self.cgImage else { return self } let contextImage: UIImage = UIImage(cgImage: cgimage) var cropWidth: CGFloat = size.width var cropHeight: CGFloat = size

A View Class for Cropping Images, MMSCropImageView is a subclass of UIImageView . It provides the features for dragging a rectangle over the view, moving it, clearing it, and  You use image objects to represent image data of all kinds, and the UIImage class is capable of managing data for all image formats supported by the underlying platform. . Image objects are immutable, so you always create them from existing image data, such as an image file on disk or programmatically created image d

Comments
  • If you're trying to diagnose a crash, you should be running the app under the debugger and making note of what happens when it crashes. You haven't even identified if there is an exception being thrown or you're getting EXC_BAD_ACCESS due to a dangling pointer. Once you know that, then you can start making theories.
  • Fair enough. I haven't repro'd this under the debugger, though I do have EXC_BAD_ACCESS messages in the crash log. When I posted this, I was working under the assumption that I'd made a stupid mistake in my implementation and somebody would jump on it (like forgetting a clipping path).
  • For what it's worth and good answers below notwithstanding, there is a good survey of techniques and performance thereof on NSHipster: nshipster.com/image-resizing. The purist in me wanted to use CIImage, but the pragmatist chose UIKit / image context.
  • When the imageOrientation is set to anything but up, the CGImage is rotated with respect to the UIImage and the cropping rectangle will be wrong. You can rotate the cropping rectangle accordingly, but the freshly created UIImage will have imageOrientation up, so that the cropped CGImage will be rotated inside it.
  • I want to point out that on the retina display you need to double your cropRect width & height using this method. Just something I ran into.
  • to make it works in any orientation use: [UIImage imageWithCGImage:imageRef scale:largeImage.scale orientation:largeImage.imageOrientation];
  • You should add support for Retina!!
  • @NicosKaralis that will only rotate it into the right orientation. However the area, that you're cropping out of the image will still be wrong.
  • You could just kill the conditional here and always multiple by self.scale, no?
  • You're right, Michael, but I think the above solution is a tiny bit faster on non-retina devices as it only does a single check instead of four multiplications plus an assignment. On retina-devices it's just a single boolean check more than necessary, so it's a question of personal preference or target fit.
  • Is it right to use CGImageRelease(imageRef); with ARC enabled?
  • @Dschee Yes. See stackoverflow.com/questions/7800174/…