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开发者_StackOverflow中文版 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.
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! :)
Use CGBitmapContextCreate()
to create a memory based bitmap for yourself. Then call CGBitmapContextGetData()
to get a pointer for your drawing code. Then CGBitmapContextCreateImage()
to create a CGImageRef
.
I hope this is sufficient to get you started.
On Mac OS you could do it with an NSBitmapImageRep. For iOS it seems to be a bit more complicated. I found this blog post though:
http://paulsolt.com/2010/09/ios-converting-uiimage-to-rgba8-bitmaps-and-back/
精彩评论