Phoney, there are some problems with your code. In particular, the last parameter takes a CGBitmapInfo type, but you're passing a CGImageAlphaInfo type. This can chop off the byte ordering information stored in CGBitmapInfo, resulting in odd problems such as pink-tinted images. Also, you're hard coding the bytesPerRow value when in fact it should be based on the original image. The following is a revised version of your code:
Code:
// Returns a rescaled copy of the image; its imageOrientation will be UIImageOrientationUp
// If the new size is not integral, it will be rounded up
- (UIImage *)makeResizedImage:(CGSize)newSize quality:(CGInterpolationQuality)interpolationQuality {
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
CGImageRef imageRef = self.CGImage;
// Compute the bytes per row of the new image
size_t bytesPerRow = CGImageGetBitsPerPixel(imageRef) / CGImageGetBitsPerComponent(imageRef) * newRect.size.width;
bytesPerRow = (bytesPerRow + 15) & ~15; // Make it 16-byte aligned
// Build a bitmap context that's the same dimensions as the new size
CGContextRef bitmap = CGBitmapContextCreate(NULL,
newRect.size.width,
newRect.size.height,
CGImageGetBitsPerComponent(imageRef),
bytesPerRow,
CGImageGetColorSpace(imageRef),
CGImageGetBitmapInfo(imageRef));
CGContextSetInterpolationQuality(bitmap, interpolationQuality);
// Draw into the context; this scales the image
CGContextDrawImage(bitmap, newRect, imageRef);
// Get the resized image from the context and a UIImage
CGImageRef resizedImageRef = CGBitmapContextCreateImage(bitmap);
UIImage *resizedImage = [UIImage imageWithCGImage:resizedImageRef];
// Clean up
CGContextRelease(bitmap);
CGImageRelease(resizedImageRef);
return resizedImage;
}
As with your original function, this code works as expected only when UIImage.imageOrientation == UIImageOrientationUp.
because I'm more familiar with that syntax, but I need to know how to complete the line that calls the funtion or method, passing an image and a rect, and creating a UIImage that I can then use.
Sorry. Total brain f**t. I guess I was so excited to find this post, phoney's code, and also especially the code you referred us to, which takes image orientation into account. *Incredibly* useful for the app I'm working on. Lifesaver. Thanks.
// There's a wierdness with kCGImageAlphaNone and CGBitmapContextCreate
// see Supported Pixel Formats in the Quartz 2D Programming Guide
// Creating a Bitmap Graphics Context section
// only RGB 8 bit images with alpha of kCGImageAlphaNoneSkipFirst, kCGImageAlphaNoneSkipLast, kCGImageAlphaPremultipliedFirst,
// and kCGImageAlphaPremultipliedLast, with a few other oddball image kinds are supported
// The images on input here are likely to be png or jpeg files