将一张图片转换成16位色深的图片。

3

我正在寻找一种优化图片的方法,通过将其颜色从32位转换为16位,而不仅仅是简单地调整大小。因此,这是我的做法:

- (UIImage *)optimizeImage:(UIImage *)image
{
    float newWidth = image.size.width;
    float newHeight = image.size.height;

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, newWidth, newHeight, 5, newWidth * 4,
                                                 colorSpace, kCGImageAlphaNone | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    CGInterpolationQuality quality = kCGInterpolationHigh;
    CGContextSetInterpolationQuality(context, quality);

    CGImageRef srcImage = CGImageRetain(image.CGImage);

    CGContextDrawImage(context, CGRectMake(0, 0, newWidth, newHeight),
                       srcImage);
    CGImageRelease(srcImage);
    CGImageRef dst = CGBitmapContextCreateImage(context);
    CGContextRelease(context);

    UIImage *result = [UIImage imageWithCGImage:dst];
    CGImageRelease(dst);

    UIGraphicsEndImageContext();

    return result;
}

这段代码存在的问题在于,当我运行它时,出现了以下错误提示:
CGBitmapContextCreate: 不支持的参数组合:5个整数位/组件;16位/像素; 3成分颜色空间;kCGImageAlphaNone;10392字节/行。
因此,我的问题是:CGBitmapContextCreate所支持的组合是什么?在这种情况下,bitmapInfo参数应选择什么呢?请给予建议。
1个回答

6
所以我在Mac开发者文库中找到了答案。这里有一个支持的像素格式表格,这就是我所需要的:

RGB - 16 bpp,5 bpc,kCGImageAlphaNoneSkipFirst

所以我改变了我的bitmapInfo,上下文创建得非常好。希望这对某些人有用。

那个不保留 alpha 通道。 - DanielZanchi
但我发现使用UIImage显示时,内存使用不够优化。 - John

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接