views:

502

answers:

2

I'm using the following code to crop and create a new UIImage out of a bigger one. I've isolated the issue to be with the function CGImageCreateWithImageInRect() which seem to not set some CGImage property the way I want. :-) The problem is that a call to function UIImagePNGRepresentation() fails returning a nil.

CGImageRef origRef = [stillView.image CGImage];
CGImageRef cgCrop = CGImageCreateWithImageInRect( origRef, theRect);
UIImage *imgCrop = [UIImage imageWithCGImage:cgCrop];

...

NSData *data = UIImagePNGRepresentation ( imgCrop);

-- libpng error: No IDATs written into file

Any idea what might wrong or alternative for cropping a rect out of UIImage? Many thanks!

A: 

In a PNG there are various chunks present, some containing palette info, some actual image data and some other information, it's a very interesting standard. The IDAT chunk is the bit that actually contains the image data. If there's no "IDAT written into file" then libpng has had some issue creating a PNG from the input data.

I don't know exactly what your stillView.image is, but what happens when you pass your code a CGImageRef that is certainly valid? What are the actual values in theRect? If your theRect is beyond the bounds of the image then the cgCrop you're trying to use to make the UIImage could easily be nil - or not nil, but containing no image or an image with width and height 0, giving libpng nothing to work with.

Adam Eberbach
Thank you for the answer. stillView is UIImageView. I peeked the property and function return values of cgCrop and imgCrop with gdb p/po commands and both seem to have correct dimension, imgCrop CGImage reference points to cgCrop etc. Hmmm. Will have a more detailed look when back from work.
Ari J.R.
A: 

It seems the soultion you are trying should work, but i recommend to use this:

CGImageRef image = [stillView.image CGImage];
CGRect cropZone;

size_t cWitdh = cropZone.size.width;
size_t cHeight = cropZone.size.height;
size_t bitsPerComponent = CGImageGetBitsPerComponent(image);
size_t bytesPerRow = CGImageGetBytesPerRow(image) / CGImageGetWidth(image) * cWidth;

//Now we build a Context with those dimensions.
CGContextRef context = CGBitmapContextCreate(nil, cWitdh, cHeight, bitsPerComponent, bytesPerRow, CGColorSpaceCreateDeviceRGB(), CGImageGetBitmapInfo(image));

CGContextDrawImage(context, cropZone, image);

CGImageRef result  = CGBitmapContextCreateImage(context);
UIImage * cropUIImage = [[UIImage alloc] initWithCGImage:tmp];

CGContextRelease(context);
CGImageRelease(mergeResult);
NSData * imgData = UIImagePNGRepresentation ( cropUIImage);

Hope it helps.

sicario