Editing UIImage
I have a UIImage that I want to edit (let's say make every second row of pixels black). Now I know about functions that extract data from PNG or JPEG image, but this is raw data and I don't know how png / jpeg files work. Is there a way that I can extract the color data from each pixel into an array? And then create a new UIImage using the data from the array?
a source to share
Create a CGBitmapContext and draw a UIImage CGImage into it . Cobbier pixel bytes and then create a new CGImage ( and UIImage if required) from the bytes.
The main reason is that CGImage supports a wide range of pixel formats, which would be unattractive for you to try to support if you were trying to work with whatever format the given CGImage was created with.
a source to share
Here are the steps I took to do something like this (this creates a bitmap context for an 8-bit grayscale with 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 the docs say you can pass NULL in the bitmapData parameter and malloc'ing the whole memory array. I found that if you do this, you cannot use CGBitmapContextGetData to force the pointer to go through the byte data.
// Draw the image into the context
CGContextDrawImage(context, CGRectMake(0, 0, pixelsWide, pixelsHigh), imageRef);
To read the pixel at position i in the data use:
unsigned char *pointerToPixelData = CGBitmapContextGetData(context);
pixelValue = *(pointerToPixelData + i);
Remember to free everything and free the malloc'd memory when you're done.
Hope it helps,
Dave
a source to share