2013-10-01 242 views
1

這種情況下,iOS - 如何將png圖像轉換爲4位位圖灰度?

我想使用iOS6 +將PNG圖像(或JPEG)轉換爲4位位圖灰度圖像,即4位位圖只需要支持16灰度顏色。

我該怎麼辦?

在此先感謝。

+0

http://stackoverflow.com/questions/1298867/convert-image-to-grayscale – Spynet

+0

謝謝,我會檢查它,代碼讓我有些事情要做。 –

回答

0

你可以將它轉換爲8位灰度圖像(見Convert UIImage to 8 bits,或見the link that Spynet shared包括其他排列),但我無法適應,要創建4位灰度位圖(CGBitmapContextCreate抱怨說,它不是一個有效的參數組合)。它看起來應該是理論上可行的(有012位的,pixel format types下列出的4位格式),但我無法讓它工作這種技術。

+0

感謝您的回答,我會檢查它。 –

0

我找到了將圖像轉換爲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的紋理使用。

+0

iOS 8,現在給出一個警告:'將枚舉類型'enum CGImageAlphaInfo'隱式轉換爲不同的枚舉類型'CGBitmapInfo'(又名'enum CGBitmapInfo')' –

相關問題