0
votes

For a method to physically scale any UIImage, I need to create bitmap context that has exact same settings as the image except for target width and height.

Here is my code so far. What is missing: How can I determine number of components per pixel of a CGImage for the bytesPerRow parameter of CGBitmapContextCreate?

CGImageRef cgImage = self.CGImage;
size_t widthPX = CGImageGetWidth(cgImage);
size_t heightPX = CGImageGetHeight(cgImage);
size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage);
size_t bitsPerPixel = CGImageGetBitsPerPixel(cgImage);
size_t bytesPerRow = CGImageGetBytesPerRow(cgImage);
CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage);
CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(cgImage);

CGContextRef ctx = CGBitmapContextCreate(NULL, destWidth, destHeight, bitsPerComponent, bytesPerRow /wrong!! it is for source width!/, colorSpace, bitmapInfo);

1

1 Answers

4
votes

Here is my crude solution. I am not yet sure if it is working.

size_t bytesPerRow = CGImageGetBytesPerRow(cgImage);
size_t bytesPerPixel = bytesPerRow / widthPX;
size_t destBytesPerRow = bytesPerPixel * destWidth;

What I tried to do is this: First, calculate bytes per pixel based on bytes per row and number of pixels in source image. Then multiply this with destination width to get bytes per row of destination image.