开发者社区> 问答> 正文

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

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

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

展开
收起
a123456678 2016-07-20 15:56:43 2513 0
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]);
        }
    }
    2019-07-17 19:59:00
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载