上面是我要读取的灰度图,单通道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。为什么是这样?
你calloc完_heightData 就去BitmapContextCreate了,肯定是0啊。imageRef压根就没用到- -。