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

用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。为什么是这样?


你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]);
    }
}
【热门文章】
【热门文章】