ios - 将 24 位 PNG 图像转换为 GLubytes 数组

标签 ios objective-c opengl-es png

我想做以下事情:

  1. 从 24 位 PNG 图像中读取 RGB 颜色值
  2. 平均 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 色彩空间): enter image description here

最佳答案

如果参数b,请检查一些日志记录, gr在最后一个 for 中产生正常值环形。你弄错的地方是indexedData[j++] = (r + g + b) / 3;这 3 个参数是 1 个字节的 sizeof,你不能这样总结它们。使用更大的整数,对它们进行类型转换并将结果类型转换回数组。 (你很可能会溢出)

关于ios - 将 24 位 PNG 图像转换为 GLubytes 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16273330/

相关文章:

iphone - iOS 5 在现有应用程序中使用 Storyboards 实现页面 Controller

iphone - 从另一个类调用时对象为零

objective-c - 将任何数据类型转换为 NSData 并再次返回

Android opengl es YUV to RGB conversion using shaders

ios - 重定向到 native 邮件应用程序的 AppStore

ios - 在图像上绘画 (UIImageView) ipad 应用程序

ios - LinearGravityField() 不影响场景 SceneKit 中的物理体

iPhone 在状态栏中添加图标(a la Battery Indicator)

ios 如何用纹理替换相机预览中的颜色

ios - glBlendColor 不适用于 iOS