简体   繁体   English

降低UIImage的质量(压缩它)

[英]Reducing the quality of a UIImage (compressing it)

Hi I am trying to compress a UIImage my code is like so: 嗨,我正在尝试压缩UIImage我的代码是这样的:

    var data = UIImageJPEGRepresentation(image, 1.0)
    print("Old image size is \(data?.length) bytes")
    data = UIImageJPEGRepresentation(image, 0.7)
    print("New image size is \(data?.length) bytes")
    let optimizedImage = UIImage(data: data!, scale: 1.0)

The print out is: 打印输出为:

Old image size is Optional(5951798) bytes
New image size is Optional(1416792) bytes

Later on in the app I upload the UIImage to a webserver (it's converted to NSData first). 稍后在应用程序中,我将UIImage上传到Web服务器(首先将其转换为NSData)。 When I check the size it's the original 5951798 bytes. 当我检查大小时,它是原始的5951798字节。 What could I be doing wrong here? 我在这里可能做错了什么?

A UIImage provides a bitmap (uncompressed) version of the image which can be used for rendering the image to screen. UIImage提供图像的位图(未压缩)版本,可用于将图像渲染到屏幕上。 The JPEG data of an image can be compressed by reducing the quality (the colour variance in effect) of the image, but this is only in the JPEG data. 可以通过降低图像的质量(有效的颜色变化)来压缩图像的JPEG数据,但这仅在JPEG数据中。 Once the compressed JPEG is unpacked into a UIImage it again requires the full bitmap size (which is based on the colour format and the image dimensions). 将压缩的JPEG解压缩到UIImage它再次需要完整的位图大小(基于颜色格式和图像尺寸)。

Basically, keep the best quality image you can for display and compress just before upload. 基本上,请确保在上传之前可以显示和压缩最佳质量的图像。

Send this data to server data = UIImageJPEGRepresentation(image, 0.7) , instead of sending optimizedimage to server. 将此数据发送到服务器数据= UIImageJPEGRepresentation(image,0.7) ,而不是将优化的 图像发送到服务器。

You already compressed the image to data. 您已经将图像压缩为数据。 So it will be repeating process(resetting to original size). 因此,这将是重复的过程(重置为原始大小)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM