用UIImage读取灰度图像素数据为0

灰度图

上面是我要读取的灰度图,单通道8位。我用了UIImageCGImage来读取这张图的像素数据:

UIImage *heightmap = [UIImage imageNamed:[_terrainFiles valueForKey:HEIGHTMAP]];
    CGImageRef imageRef = [heightmap CGImage];
    _width = CGImageGetWidth(imageRef);
    _height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    _heightData = (unsigned char*)calloc(_width * _height, sizeof(unsigned char));
    NSUInteger bytesPerPixel = 1;
    NSUInteger bytesPerRow = bytesPerPixel * _width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(_heightData, _width, _height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaNone);
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);

    for (int i = 0; i < _width * _height; i++) {
        if (_heightData[i] != 0) {
            printf("%hhd ", _heightData[i]);
        }
        //printf("\n");
    }

下面我打印了读出来的数据,全是0。为什么是这样?

阅读 8k
1 个回答

你calloc完_heightData 就去BitmapContextCreate了,肯定是0啊。imageRef压根就没用到- -。

UIImage *heightmap = [UIImage imageNamed:[_terrainFiles valueForKey:HEIGHTMAP]];
CGImageRef imageRef = [heightmap CGImage];
_width = CGImageGetWidth(imageRef);
_height = CGImageGetHeight(imageRef);

CGDataProviderRef provider = CGImageGetDataProvider(cgimage);
NSData* data = (id)CGDataProviderCopyData(provider);

const uint8_t *heightData = [data bytes];
for (int i = 0; i < _width * _height; i++)
{
    if (heightData[i] != 0)
    {
        printf("%hhd ", _heightData[i]);
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏