Create image from RGB data?

I have real problems with this. I have some raw rgb data, values ​​from 0 to 255, and you want to display them as an image on iphone, but cannot find out how to do this. Can anyone help? I think I may have to use CGImageCreate, but just don't understand. Tried to take a look at the cool link and feel pretty stuck.

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

+5
source share
3 answers

a terribly primitive example similar to Matz's 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! :)
+13
source

Use CGBitmapContextCreate()to create a memory-based bitmap for yourself. Then call CGBitmapContextGetData()to get a pointer to the drawing code. Then CGBitmapContextCreateImage()create CGImageRef.

Hope this is enough to get you started.

+2
source

All Articles