【问题标题】:Convert UIImage to 8 bits将 UIImage 转换为 8 位
【发布时间】:2013-06-22 05:14:41
【问题描述】:

我希望将 UIImage 转换为 8 位。我曾尝试这样做,但我不确定我是否做得对,因为稍后当我尝试使用图像处理库 leptonica 时收到一条消息,指出它不是 8 位。谁能告诉我我是否正确执行此操作或有关如何执行此操作的代码?

谢谢!

代码

 CGImageRef myCGImage = image.CGImage;
 CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(myCGImage));
 const UInt8 *imageData = CFDataGetBytePtr(data);

【问题讨论】:

  • 查看this 以访问原始像素数据 您必须转换为 8 位。如果事先知道格式,那就很简单了,例如对于 RGBA,只需找到 R、G、B 通道的平均值。
  • 我认为他的意思是灰度。 Leptonica 是一个图像处理库。大多数图像处理库都处理灰度图像。

标签: ios objective-c


【解决方案1】:

以下代码适用于没有 alpha 通道的图像:

    CGImageRef c = [[UIImage imageNamed:@"100_3077"] CGImage];

    size_t bitsPerPixel = CGImageGetBitsPerPixel(c);
    size_t bitsPerComponent = CGImageGetBitsPerComponent(c);
    size_t width = CGImageGetWidth(c);
    size_t height = CGImageGetHeight(c);

    CGImageAlphaInfo a = CGImageGetAlphaInfo(c);

    NSAssert(bitsPerPixel == 32 && bitsPerComponent == 8 && a == kCGImageAlphaNoneSkipLast, @"unsupported image type supplied");

    CGContextRef targetImage = CGBitmapContextCreate(NULL, width, height, 8, 1 * CGImageGetWidth(c), CGColorSpaceCreateDeviceGray(), kCGImageAlphaNone);

    UInt32 *sourceData = (UInt32*)[((__bridge_transfer NSData*) CGDataProviderCopyData(CGImageGetDataProvider(c))) bytes];
    UInt32 *sourceDataPtr;

    UInt8 *targetData = CGBitmapContextGetData(targetImage);

    UInt8 r,g,b;
    uint offset;
    for (uint y = 0; y < height; y++)
    {
        for (uint x = 0; x < width; x++)
        {
            offset = y * width + x;

            if (offset+2 < width * height)
            {
                sourceDataPtr = &sourceData[y * width + x];

                r = sourceDataPtr[0+0];
                g = sourceDataPtr[0+1];
                b = sourceDataPtr[0+2];

                targetData[y * width + x] = (r+g+b) / 3;
            }
        }
    }

    CGImageRef newImageRef = CGBitmapContextCreateImage(targetImage);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];

    CGContextRelease(targetImage);
    CGImageRelease(newImageRef);

使用此代码,我将 rgb 图像转换为灰度图像:

希望对你有帮助

【讨论】:

  • 我用asia.olympus-imaging.com/products/dslr/e510/sample/images/… 试过这个,它在图​​像的最底部出现访问冲突。
  • 嗯,我用你发布的图片试过了,我得到了同样的错误。最后一个像素似乎有所不同...我已经更新了代码,所以我们不能超出图像的边界。
猜你喜欢
  • 1970-01-01
  • 2019-05-23
  • 2012-08-04
  • 2015-08-04
  • 2014-07-25
  • 2021-12-16
  • 2014-08-18
  • 1970-01-01
  • 2015-07-30
相关资源
最近更新 更多