1
我想输出一个8位灰度位图的UIImage,但我不熟悉图像处理,所以我在如何做到这一点的损失。我遵循这个stackoverflow后(Objective C - save UIImage as a BMP file)创建一个UIImage类别,它可以成功地生成一个RGB 32位图像,但我一直无法操纵代码,让它以8位灰度输出它。我试图获取这个图像的原始字节,以传递给提供的C库。保存UIImage为8位灰度位图
是否有什么样的UIImage我想要生成位图?它可以是每个像素的位数,每个组件的位数和alpha设置?我已经尝试在没有alpha的8位UIImage上使用此代码,并且使用alpha的32位,并且都没有创建可以由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];
}
这也许[链接](https://github.com/Kalvar/ios- KRImageGrayscale)可以帮助你。 –
你是否设法使这个工作? – gomezluisj