[英]iOS - How to convert a png image to 4-bits bitmap grayscale?
這樣的話
我想使用iOS6 +將PNG圖像(或JPEG)轉換為4位位圖灰度圖像,即4位位圖僅需要支持16種灰色。
我能怎么做 ?
提前致謝。
您可以將其轉換為8位灰度圖像(請參閱將UIImage轉換為8位 ,或查看Spynet共享的鏈接,其中包括其他排列),但是我無法適應它來創建4位灰度位圖( CGBitmapContextCreate
抱怨說這不是有效的參數組合)。 從理論上講,這似乎應該是可行的( CVPixelBuffer
像素格式類型下列出了4位格式),但是我無法使這種技術起作用。
我找到了將圖像轉換為4位灰度的解決方案,代碼如下。
-(UIImage *)grayscaleImageAt4Bits:(UIImage *)_image
{
CGImageRef imageRef = [_image CGImage];
int width = CGImageGetWidth(imageRef);
int height = CGImageGetHeight(imageRef);
NSInteger _bitsPerComponent = 8;
NSInteger _bytesPerPixel = 1;
NSInteger _bytesPerRow = _bytesPerPixel * width;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
uint8_t *sourceData = malloc(height * width * _bytesPerPixel);
CGContextRef context = CGBitmapContextCreate(sourceData,
width,
height,
_bitsPerComponent,
_bytesPerRow,
colorSpace,
kCGImageAlphaNone);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
const int _redIndex = 0;
const int _greenIndex = 1;
const int _blueIndex = 2;
int _byteIndex = 0;
int _bitIndex = 0;
uint8_t *_newImageBits = malloc( height * width * _bytesPerPixel / 2 );
for(int j=0;j<height;j++)
{
for(int k=0;k<width;k++)
{
UInt8 _perPixel = _newImageBits[_byteIndex];
UInt8 *rgbPixel = (UInt8 *) &sourceData[j * width + k];
int _red = rgbPixel[_redIndex];
int _green = rgbPixel[_greenIndex];
int _blue = rgbPixel[_blueIndex];
int _pixelGrayValue = (_green + _red + _blue) / 16;
UInt8 _pixelByte = (UInt8)_pixelGrayValue;
_perPixel |= (_pixelByte<<4);
_newImageBits[_byteIndex] = _perPixel;
_bitIndex += 4;
if(_bitIndex > 7)
{
_byteIndex++;
_bitIndex = 0;
}
}
}
free(sourceData);
//Direct fetch Bytes of 4-Bits, then you can use this Bytes ( sourceData ) to do something.
sourceData = _newImageBits;
CGImageRef cgImage = CGBitmapContextCreateImage(context);
UIImage *_grayImage = [UIImage imageWithCGImage:cgImage];
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
//Convert to NSData type, then you can use this NSData ( _sourceImageData ) to do something.
NSData *_sourceImageData = [NSData dataWithBytes:sourceData length:(width * height * _bytesPerPixel)];
free(sourceData);
return _grayImage;
}
而且iOS僅支持顯示最少8位的顏色,因此4位數據僅傳輸到openGL的紋理以供使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.