Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I autocrop a UIImage?

I have a UIImage which contains a shape; the rest is transparent. I'd like to get another UIImage by cropping out as much of the transparent part as possible, still retaining all of the non-transparent pixels - similar to the autocrop function in GIMP. How would I go about doing this?

like image 664
Simon Avatar asked Jan 30 '12 09:01

Simon


People also ask

How do you declare UIImage in Objective C?

For example: UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]]; My UIImage object is declared in .

How do I find my UIImage path?

Once a UIImage is created, the image data is loaded into memory and no longer connected to the file on disk. As such, the file can be deleted or modified without consequence to the UIImage and there is no way of getting the source path from a UIImage.

How do I render UIView to UIImage?

extension UIView { // Using a function since `var image` might conflict with an existing variable // (like on `UIImageView`) func asImage() -> UIImage { if #available(iOS 10.0, *) { let renderer = UIGraphicsImageRenderer(bounds: bounds) return renderer. image { rendererContext in layer. render(in: rendererContext.


2 Answers

This approach may be a little more invasive than what you were hoping for, but it gets the job done. What I'm doing is creating a bitmap context for the UIImage, obtaining a pointer to the raw image data, then sifting through it looking for non-transparent pixels. My method returns a CGRect which I use to create a new UIImage.

- (CGRect)cropRectForImage:(UIImage *)image {

CGImageRef cgImage = image.CGImage;
CGContextRef context = [self createARGBBitmapContextFromImage:cgImage];
if (context == NULL) return CGRectZero; 

size_t width = CGImageGetWidth(cgImage);
size_t height = CGImageGetHeight(cgImage);
CGRect rect = CGRectMake(0, 0, width, height);

CGContextDrawImage(context, rect, cgImage);

unsigned char *data = CGBitmapContextGetData(context);
CGContextRelease(context);

//Filter through data and look for non-transparent pixels.
int lowX = width;
int lowY = height;
int highX = 0;
int highY = 0;
if (data != NULL) {
    for (int y=0; y<height; y++) {
        for (int x=0; x<width; x++) {
            int pixelIndex = (width * y + x) * 4 /* 4 for A, R, G, B */;
            if (data[pixelIndex] != 0) { //Alpha value is not zero; pixel is not transparent.
                if (x < lowX) lowX = x;
                if (x > highX) highX = x;
                if (y < lowY) lowY = y;
                if (y > highY) highY = y;
            }
        }
    }
    free(data);
} else {
    return CGRectZero;
}

return CGRectMake(lowX, lowY, highX-lowX, highY-lowY);
}

The method to create the Bitmap Context:

- (CGContextRef)createARGBBitmapContextFromImage:(CGImageRef)inImage {

CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
void *bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;

// Get image width, height. We'll use the entire image.
size_t width = CGImageGetWidth(inImage);
size_t height = CGImageGetHeight(inImage);

// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = (width * 4);
bitmapByteCount = (bitmapBytesPerRow * height);

// Use the generic RGB color space.
colorSpace = CGColorSpaceCreateDeviceRGB();
if (colorSpace == NULL) return NULL;

// Allocate memory for image data. This is the destination in memory
// where any drawing to the bitmap context will be rendered.
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL)
{
    CGColorSpaceRelease(colorSpace);
    return NULL;
}

// Create the bitmap context. We want pre-multiplied ARGB, 8-bits
// per component. Regardless of what the source image format is
// (CMYK, Grayscale, and so on) it will be converted over to the format
// specified here by CGBitmapContextCreate.
context = CGBitmapContextCreate (bitmapData,
                                 width,
                                 height,
                                 8,      // bits per component
                                 bitmapBytesPerRow,
                                 colorSpace,
                                 kCGImageAlphaPremultipliedFirst);
if (context == NULL) free (bitmapData);

// Make sure and release colorspace before returning
CGColorSpaceRelease(colorSpace);

return context;
}

And finally, get your new cropped UIImage from the returned CGRect:

CGRect newRect = [self cropRectForImage:oldImage];
CGImageRef imageRef = CGImageCreateWithImageInRect(oldImage.CGImage, newRect);
UIImage *newImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);

I grabbed a bit of that code from this very useful article. Hope it helps!

like image 120
dalton_c Avatar answered Oct 18 '22 17:10

dalton_c


Swift Version:

extension UIImage {
func cropRect() -> CGRect {
    let cgImage = self.CGImage!
    let context = createARGBBitmapContextFromImage(cgImage)
    if context == nil {
        return CGRectZero
    }

    let height = CGFloat(CGImageGetHeight(cgImage))
    let width = CGFloat(CGImageGetWidth(cgImage))

    let rect = CGRectMake(0, 0, width, height)
    CGContextDrawImage(context, rect, cgImage)

    let data = UnsafePointer<CUnsignedChar>(CGBitmapContextGetData(context))

    if data == nil {
        return CGRectZero
    }

    var lowX = width
    var lowY = height
    var highX: CGFloat = 0
    var highY: CGFloat = 0

    //Filter through data and look for non-transparent pixels.
    for (var y: CGFloat = 0 ; y < height ; y++) {
        for (var x: CGFloat = 0; x < width ; x++) {
            let pixelIndex = (width * y + x) * 4 /* 4 for A, R, G, B */

            if data[Int(pixelIndex)] != 0 { //Alpha value is not zero pixel is not transparent.
                if (x < lowX) {
                    lowX = x
                }
                if (x > highX) {
                    highX = x
                }
                if (y < lowY) {
                    lowY = y
                }
                if (y > highY) {
                    highY = y
                }
            }
        }
    }


    return CGRectMake(lowX, lowY, highX-lowX, highY-lowY)
}
}

The method to create the Bitmap Context:

func createARGBBitmapContextFromImage(inImage: CGImageRef) -> CGContextRef? {

    let width = CGImageGetWidth(inImage)
    let height = CGImageGetHeight(inImage)

    let bitmapBytesPerRow = width * 4
    let bitmapByteCount = bitmapBytesPerRow * height

    let colorSpace = CGColorSpaceCreateDeviceRGB()
    if colorSpace == nil {
        return nil
    }

    let bitmapData = malloc(bitmapByteCount)
    if bitmapData == nil {
        return nil
    }

    let context = CGBitmapContextCreate (bitmapData,
        width,
        height,
        8,      // bits per component
        bitmapBytesPerRow,
        colorSpace,
        CGImageAlphaInfo.PremultipliedFirst.rawValue)

    return context
}

And finally, get your new cropped UIImage from the returned CGRect:

let image = // UIImage Source
let newRect = image.cropRect()
if let imageRef = CGImageCreateWithImageInRect(image.CGImage!, newRect) {
    let newImage = UIImage(CGImage: imageRef)
    // Use this new Image
}
like image 27
Sahil Kapoor Avatar answered Oct 18 '22 17:10

Sahil Kapoor