Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create image from RGB data?

I'm having real trouble with this. I have some raw rgb data, values from 0 to 255, and want to display it as an image on the iphone but can't find out how to do it. Can anyone help? I think i might need to use CGImageCreate but just don't get it. Tried looking at the class reference and am feeling quite stuck.

All I want is a 10x10 greyscale image generated from some calculations and if there is an easy way to create a png or something that would be great.

like image 714
John P Avatar asked Aug 29 '11 21:08

John P


People also ask

How do I create an RGB image in Python?

RGB images can be produced using matplotlib's ability to make three-color images. In general, an RGB image is an MxNx3 array, where M is the y-dimension, N is the x-dimension, and the length-3 layer represents red, green, and blue, respectively. A fourth layer representing the alpha (opacity) value can be specified.

How is RGB image stored?

An RGB image, sometimes referred to as a truecolor image, is stored as an m-by-n-by-3 data array that defines red, green, and blue color components for each individual pixel. RGB images do not use a palette.


1 Answers

a terribly primitive example, similar to Mats' suggestion, but this version uses an external pixel buffer (pixelData):

const size_t Width = 10;
const size_t Height = 10;
const size_t Area = Width * Height;
const size_t ComponentsPerPixel = 4; // rgba

uint8_t pixelData[Area * ComponentsPerPixel];

// fill the pixels with a lovely opaque blue gradient:
for (size_t i=0; i < Area; ++i) {
    const size_t offset = i * ComponentsPerPixel;
    pixelData[offset] = i;
    pixelData[offset+1] = i;
    pixelData[offset+2] = i + i; // enhance blue
    pixelData[offset+3] = UINT8_MAX; // opaque
}

// create the bitmap context:
const size_t BitsPerComponent = 8;
const size_t BytesPerRow=((BitsPerComponent * Width) / 8) * ComponentsPerPixel;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef gtx = CGBitmapContextCreate(&pixelData[0], Width, Height, BitsPerComponent, BytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);

// create the image:
CGImageRef toCGImage = CGBitmapContextCreateImage(gtx);
UIImage * uiimage = [[UIImage alloc] initWithCGImage:toCGImage];

NSData * png = UIImagePNGRepresentation(uiimage);

// remember to cleanup your resources! :)
like image 130
justin Avatar answered Oct 06 '22 14:10

justin