[英]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. 我有一些原始的rgb数据,其值介于0到255之间,并想将其显示为iPhone上的图像,但找不到方法。 Can anyone help? 有人可以帮忙吗? I think i might need to use CGImageCreate but just don't get it. 我想我可能需要使用CGImageCreate,但就是不明白。 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. 我想要的只是通过一些计算生成的10x10灰度图像,如果有一种简单的方法可以创建png或很棒的东西。
a terribly primitive example, similar to Mats' suggestion, but this version uses an external pixel buffer ( pixelData
): 一个非常原始的示例,类似于Mats的建议,但是此版本使用了外部像素缓冲区( 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. 使用CGBitmapContextCreate()
为您自己创建基于内存的位图。 Then call CGBitmapContextGetData()
to get a pointer for your drawing code. 然后调用CGBitmapContextGetData()
以获取绘图代码的指针。 Then CGBitmapContextCreateImage()
to create a CGImageRef
. 然后CGBitmapContextCreateImage()
创建CGImageRef
。
I hope this is sufficient to get you started. 我希望这足以让您入门。
On Mac OS you could do it with an NSBitmapImageRep. 在Mac OS上,您可以使用NSBitmapImageRep来实现。 For iOS it seems to be a bit more complicated. 对于iOS,它似乎要复杂一些。 I found this blog post though: 我发现了这篇博客文章:
http://paulsolt.com/2010/09/ios-converting-uiimage-to-rgba8-bitmaps-and-back/ http://paulsolt.com/2010/09/ios-converting-uiimage-to-rgba8-bitmaps-and-back/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.