ios - 用UIImage读取灰度图像素数据为0
迷茫
迷茫 2017-04-17 11:45:39
[iOS讨论组]

上面是我要读取的灰度图,单通道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。为什么是这样?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(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]);
    }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号