我遇到了一些困难。我有一些原始的RGB数据,值从0到255,想在iPhone上将其显示为图像,但不知道如何操作。有人能帮忙吗?我认为我可能需要使用CGImageCreate,但是不太理解。尝试查看类参考文档,但感觉很无助。
我只想生成一个10x10的灰度图像,其中包含一些计算结果,如果有一种简单的方法来创建PNG或其他格式的图像就太好了。
我只想生成一个10x10的灰度图像,其中包含一些计算结果,如果有一种简单的方法来创建PNG或其他格式的图像就太好了。
一个非常基础的例子,类似于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! :)
pixelData
是一个连续的rgba像素组件缓冲区,非常常见于C语言图形处理中。它的内存布局(单调递增)是rgbargbargbargbargba... 你可以看到我是如何通过在示例中设置pixelData
元素来生成蓝色渐变的。我不确定你具体的问题是什么...也许这个链接可以帮助你(?): http://en.wikipedia.org/wiki/Pixels - justinCGBitmapContextCreate
而不是pixelData
。或者将像素从缓冲区复制到pixelData
。 - justinCGBitmapContextCreate()
函数来创建一个基于内存的位图。接着调用CGBitmapContextGetData()
函数来获取指针,以便进行绘制操作。最后,使用CGBitmapContextCreateImage()
函数来创建一个CGImageRef
对象。在Mac OS上,您可以使用NSBitmapImageRep来完成。对于iOS来说似乎要复杂一些。不过我找到了这篇博客文章:
http://paulsolt.com/2010/09/ios-converting-uiimage-to-rgba8-bitmaps-and-back/