我想做以下事情:
- 从 24 位 PNG 图像中读取 RGB 颜色值
- 平均 RGB 值并将它们存储到 Glubytes 数组中。
我已经提供了我希望执行这两个步骤的函数。 我的函数返回一个 Glubytes 数组,但是所有元素的值为 0。 所以我猜我错误地读取了图像数据。
我在阅读图像时出了什么问题? (也许我的格式不正确)。
这是我的功能:
+ (GLubyte *) LoadPhotoAveragedIndexPNG:(UIImage *)image numPixelComponents: (int)numComponents
{
// Load an image and return byte array.
CGImageRef textureImage = image.CGImage;
if (textureImage == nil)
{
NSLog(@"LoadPhotoIndexPNG: Failed to load texture image");
return nil;
}
NSInteger texWidth = CGImageGetWidth(textureImage);
NSInteger texHeight = CGImageGetHeight(textureImage);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
GLubyte *indexedData = (GLubyte *)malloc(texWidth * texHeight);
GLubyte *rawData = (GLubyte *)malloc(texWidth * texHeight * numComponents);
CGContextRef textureContext = CGBitmapContextCreate(
rawData,
texWidth,
texHeight,
8,
texWidth * numComponents,
colorSpace,
kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(textureContext,
CGRectMake(0.0, 0.0, (float)texWidth, (float)texHeight),
textureImage);
CGContextRelease(textureContext);
int rawDataLength = texWidth * texHeight * numComponents;
for (int i = 0, j = 0; i < rawDataLength; i += numComponents)
{
GLubyte b = rawData[i];
GLubyte g = rawData[i + 1];
GLubyte r = rawData[i + 2];
indexedData[j++] = (r + g + b) / 3;
}
return indexedData;
}
这是即时加载的测试图像(PNG 格式的 RGB 色彩空间):
最佳答案
如果参数b
,请检查一些日志记录, g
和 r
在最后一个 for
中产生正常值环形。你弄错的地方是indexedData[j++] = (r + g + b) / 3;
这 3 个参数是 1 个字节的 sizeof,你不能这样总结它们。使用更大的整数,对它们进行类型转换并将结果类型转换回数组。 (你很可能会溢出)
关于ios - 将 24 位 PNG 图像转换为 GLubytes 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16273330/