【发布时间】:2015-08-04 20:15:46
【问题描述】:
我正在尝试将 UIImage 输出到 8 位灰度位图,但我对图像处理不是很熟悉,所以我不知道如何做到这一点。我按照这个 stackoverflow 帖子 (Objective C - save UIImage as a BMP file) 创建了一个 UIImage 类别,该类别可以成功生成 RGB 32 位图像,但我无法操作代码以使其以 8 位灰度输出。我正在尝试获取此图像的原始字节,以便传递给提供的 C 库。
我尝试为哪种 UIImage 生成位图是否重要?它可以是每个像素的位数、每个组件的位数和 alpha 设置吗?我曾尝试在不带 alpha 的 8 位 UIImage 和带 alpha 的 32 位 UIImage 上使用此代码,但两者都没有创建可由 OS X 打开的位图。
希望有人能帮忙!这几天我一直在敲我的头!
- (NSData *)bitmapData
{
NSData *bitmapData = nil;
CGImageRef image = self.CGImage;
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
UInt8 *rawData;
size_t bitsPerPixel = 8;
size_t bitsPerComponent = 8;
size_t bytesPerPixel = bitsPerPixel / bitsPerComponent;
size_t width = CGImageGetWidth(image);
size_t height = CGImageGetHeight(image);
size_t bytesPerRow = width * bytesPerPixel;
size_t bufferLength = bytesPerRow * height;
colorSpace = CGColorSpaceCreateDeviceGray();
if (colorSpace)
{
// Allocate memory for raw image data
rawData = (UInt8 *)calloc(bufferLength, sizeof(UInt8));
if (rawData)
{
CGBitmapInfo bitmapInfo = (CGBitmapInfo)kCGImageAlphaNone;
context = CGBitmapContextCreate(rawData,
width,
height,
bitsPerComponent,
bytesPerRow,
colorSpace,
bitmapInfo);
if (context)
{
CGRect rect = CGRectMake(0, 0, width, height);
CGContextTranslateCTM(context, 0, height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, rect, image);
bitmapData = [NSData dataWithBytes:rawData length:bufferLength];
CGContextRelease(context);
}
free(rawData);
}
CGColorSpaceRelease(colorSpace);
}
return bitmapData;
}
- (NSData *)bitmapFileHeaderData
{
CGImageRef image = self.CGImage;
UInt32 width = (UInt32)CGImageGetWidth(image);
UInt32 height = (UInt32)CGImageGetHeight(image);
t_bitmap_header header;
header.fileType = 0x4D42;
header.fileSize = (height * width) + 54;
header.reserved1 = 0;
header.reserved2 = 0;
header.bitmapOffset = 54;
header.headerSize = 40;
header.width = width;
header.height = height;
header.colorPlanes = 1;
header.bitsPerPixel = 8;
header.compression = 0;
header.bitmapSize = height * width;
header.horizontalResolution = 0;
header.verticalResolution = 0;
header.colorsUsed = 0;
header.colorsImportant = 0;
return [NSData dataWithBytes:&header length:sizeof(t_bitmap_header)];
}
- (NSData *)bitmapDataWithFileHeader
{
NSMutableData *data = [NSMutableData dataWithData:[self bitmapFileHeaderData]];
[data appendData:[self bitmapData]];
return [NSData dataWithData:data];
}
【问题讨论】:
-
也许这个link 可以帮助你。
-
你成功了吗?
标签: ios objective-c cocoa-touch bitmap core-graphics