【问题标题】:How to compress image size using UIImagePNGRepresentation - iOS?如何使用 UIImagePNGRepresentation 压缩图像大小 - iOS?
【发布时间】:2016-05-22 18:17:03
【问题描述】:

我正在使用UIImagePNGRepresentation 保存图像。结果图像大小为 30+ KB,在我的情况下这是很大的。

我尝试使用UIImageJPEGRepresentation,它允许压缩图像,因此图像保存为

如何压缩图像大小,使用UIImagePNGRepresentation

【问题讨论】:

  • 简单的答案是你不能,除非你选择妥协你的图像尺寸。 UIImagePNGRepresentation 返回图像的最小压缩尺寸,因为这是一种无损压缩方法,它不会影响图像的质量,不像 JPEG。所以唯一的可能是减少图像尺寸。
  • @AyanSengupta 这不是真的,有多种方法可以让 PNG 图像获得更好的压缩效果(不同的膨胀设置、使用的不同设置、调色板),但要选择最好的,我们会有全部尝试。有一些特殊的工具可以优化 PNG 图像,但我们不能指望一个简单的图形编码器来做到这一点。
  • 如果您的图像没有很多颜色,您可以使用通常较小的 PNG-8(带有 256 调色板的 PNG)。强制 UIImagePNGRepresentation 生成这种格式可能很困难,因此您可能想尝试将UIImage 转换为 rgb 数据,然后尝试使用不同的 PNG 编码器,例如库.最后,这一切都取决于您拥有的图像。
  • @Sulthan,你是对的。但我认为我们谈论的是一些不同的背景。用户问我们是否可以使用UIImagePNGRepresentation 来减小图像大小,我们绝对无法使用该 API 来做到这一点。显然,有一些可用的第三方 API 可能会被使用。不幸的是,原生 UIImagePNGRepresentation 已经做到了最好:(
  • 谢谢你们提供的信息!所以我认为我需要减小尺寸以减小尺寸。我目前的尺寸是 118x118。必须尝试一些更小的东西:|

标签: ios objective-c uiimage uiimagejpegrepresentation uiimagepngrepresentation


【解决方案1】:

PNG 使用无损压缩,这就是 UIImagePNGRepresentation 不像 UIImageJPEGRepresentation 那样接受compressionQuality 参数的原因。使用不同的工具可能会得到更小的 PNG 文件,但与 JPEG 不同。

【讨论】:

    【解决方案2】:

    也许这会对你有所帮助:

    - (void)resizeImage:(UIImage*)image{
    
        NSData *finalData = nil;
        NSData *unscaledData = UIImagePNGRepresentation(image);
    
        if (unscaledData.length > 5000.0f ) {
    
    
           //if image size is greater than 5KB dividing its height and width maintaining proportions
    
    
            UIImage *scaledImage = [self imageWithImage:image andWidth:image.size.width/2 andHeight:image.size.height/2];
            finalData = UIImagePNGRepresentation(scaledImage);
    
            if (finalData.length > 5000.0f ) {
    
                [self resizeImage:scaledImage];
            }
            //scaled image will be your final image
        }
    }
    

    调整图片大小

    - (UIImage*)imageWithImage:(UIImage*)image andWidth:(CGFloat)width andHeight:(CGFloat)height
    {
        UIGraphicsBeginImageContext( CGSizeMake(width, height));
        [image drawInRect:CGRectMake(0,0,width,height)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext() ;
        return newImage;
    }
    

    【讨论】:

    • 可以在后台队列中完成吗? (.UIGraphicsBeginImageContext)