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