具有新alpha颜色的UIImageJPEGRepresentation(背景颜色)

时间:2015-04-21 00:12:59

标签: ios uiimage uikit core-graphics core-image

我有一个部分透明的UIImage,我想将其转换为JPEG。

  

NSData * output = UIImageJPEGRepresentation(myUIImage,.90);

JPEG始终具有白色背景。我希望它是黑色的。我怎样才能做到这一点?

表现是一个问题。图像刚刚在CoreImage中渲染,在那里也可以设置背景颜色。

CIFilter *filter = [CIFilter filterWithName:@"CIPixellate"];
[filter setDefaults];
[filter setValue:[CIImage imageWithCGImage:editImage.CGImage] forKey:kCIInputImageKey];
[filter setValue:@(amount) forKey:@"inputScale"];
[filter setValue:vector forKey:@"inputCenter"];
CIImage* result = [filter valueForKey:kCIOutputImageKey];

目前我立即将'result'重新渲染为新的UIGraphicsImageContext

    CGContextSetFillColorWithColor(ref, backgroundFillColor.CGColor);
    CGRect drawRect = (CGRect){{0,0},editImage.size};
    CGContextFillRect(ref, drawRect);
    CGContextDrawImage(ref, drawRect, cgImage);
    UIImage* filledImage = UIGraphicsGetImageFromCurrentImageContext();

但与跳过步骤和白色JPEG背景相比,执行时间增加了82%。

我非常感谢你的帮助。谢谢。

更新:我尝试了以下CISourceOverCompositing,在某些情况下,运行时间增加了198%

CIFilter * constantColorFilter = [CIFilter filterWithName:@"CIConstantColorGenerator"];
[constantColorFilter setValue:[CIColor colorWithCGColor:[backgroundFillColor CGColor]] forKey:kCIInputColorKey];

CIFilter * composeFilter = [CIFilter filterWithName:@"CISourceOverCompositing"];
CIImage * bgColorResult = [constantColorFilter valueForKey:kCIOutputImageKey];
[composeFilter setValue:bgColorResult forKey:kCIInputBackgroundImageKey];
[composeFilter setValue:pixelateResult forKey:kCIInputImageKey];
result = [composeFilter valueForKey:kCIOutputImageKey];

我尝试使用单例CIFilter来避免重新创建CIFilter对象,但它对性能产生了微不足道的影响。

1 个答案:

答案 0 :(得分:0)

我的性能次优(运行时间增加80%),但这就是我现在使用的:

CIFilter *pixelateFilter = [CIFilter filterWithName:@"CIPixellate"];
[pixelateFilter setDefaults];
[pixelateFilter setValue:[CIImage imageWithCGImage:editImage.CGImage] forKey:kCIInputImageKey];
[pixelateFilter setValue:@(amount) forKey:@"inputScale"];
[pixelateFilter setValue:vector forKey:@"inputCenter"];
CIImage* result = [pixelateFilter valueForKey:kCIOutputImageKey];    
CIContext *context = [CIContext contextWithOptions:nil];
CGRect extent = [pixelateResult extent];
CGImageRef cgImage = [context createCGImage:result fromRect:extent];

UIGraphicsBeginImageContextWithOptions(editImage.size, YES, [editImage scale]);
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ref, 0, editImage.size.height);
CGContextScaleCTM(ref, 1.0, -1.0);

CGContextSetFillColorWithColor(ref, backgroundFillColor.CGColor);
CGRect drawRect = (CGRect){{0,0},editImage.size};
CGContextFillRect(ref, drawRect);
CGContextDrawImage(ref, drawRect, cgImage);
UIImage* filledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnImage = filledImage;

CGImageRelease(cgImage);