views:

72

answers:

2
+2  Q: 

Editing an UIImage

I have an UIImage that I want to edit (say, make every second row of pixels black). Now I am aware of the functions that extract PNG or JPEG data from the image, but that's raw data and I have no idea how the png/jpeg files work. Is there a way I can extract the colour data from each pixel into an array? And then make a new UIImage using the data from the array?

A: 

Create a CGBitmapContext and draw the UIImage's CGImage into it. Clobber pixel bytes as appropriate, then create a new CGImage (and UIImage, if desired) from the bytes.

The main reason to do this is that CGImage supports a wide variety of pixel formats, which would not be fun for you to try to support if you were to try to work with whatever format a given CGImage had happened to have been created with.

Peter Hosey
A: 

Here's the steps I took to do something similar (this creates a bitmap context for 8 bit greyscale no alpha:

// Allocate memory for image data.
bitmapData = malloc(bitmapByteCount);

// Use the generic Grey color space.
colorSpace = CGColorSpaceCreateDeviceGray();

// Create the bitmap context.
context = CGBitmapContextCreate (bitmapData, pixelsWide, pixelsHigh, 8, bitmapBytesPerRow, colorSpace, kCGImageAlphaNone);

Now it says in the docs that you can pass NULL to the bitmapData parameter and have the method handle all the malloc'ing of memory. I have found that if you do that, you can't then use CGBitmapContextGetData to get the pointer to go through the byte data.

// Draw the image into the context
CGContextDrawImage(context, CGRectMake(0, 0, pixelsWide, pixelsHigh), imageRef);

To read a pixel at position i in the data, use:

unsigned char *pointerToPixelData = CGBitmapContextGetData(context);
pixelValue = *(pointerToPixelData + i);

Don't forget to release everything and free malloc'd memory when you're done.

Hope this helps,

Dave

Magic Bullet Dave