压缩质量和快速缩小图像大小(高度和宽度)之间的差异



在下面的代码中,我通过降低压缩质量和大小将图像上传到服务器(图像的高度和宽度。但我想知道在这两种情况下到底发生了什么。如果我只降低压缩质量或只压缩属性的高度和宽,会发生什么?谁能解释一下这个概念吗?

func compressImage() -> UIImage? {
enum JPEGQuality: CGFloat {
case lowest  = 0
case low     = 0.25
case medium  = 0.5
case high    = 0.75
case highest = 1
}
// Reducing file size to a 10th
var actualHeight: CGFloat = self.size.height
var actualWidth: CGFloat = self.size.width
print("DEBUG: actualHeight (actualHeight)")
print("DEBUG: actualWidth (actualWidth)")
//For iphone 5s
let maxHeight: CGFloat = 1136.0
let maxWidth: CGFloat = 640.0

var imgRatio: CGFloat = actualWidth/actualHeight
let maxRatio: CGFloat = maxWidth/maxHeight
var compressionQuality: CGFloat = JPEGQuality.highest.rawValue
if actualHeight > maxHeight || actualWidth > maxWidth {
compressionQuality = JPEGQuality.high.rawValue
if imgRatio < maxRatio {
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight
actualWidth = imgRatio * actualWidth
actualHeight = maxHeight
print("DEBUG: actualHeight after compression  (actualHeight)")
print("DEBUG: actualWidth after compression (actualWidth)")
} else if imgRatio > maxRatio {
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth
actualHeight = imgRatio * actualHeight
actualWidth = maxWidth
print("DEBUG: actualHeight after compression  (actualHeight)")
print("DEBUG: actualWidth after compression (actualWidth)")
} else {
actualHeight = maxHeight
actualWidth = maxWidth
compressionQuality = JPEGQuality.highest.rawValue
print("DEBUG: actualHeight after compression  (actualHeight)")
print("DEBUG: actualWidth after compression (actualWidth)")
}
}
let rect = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight)
UIGraphicsBeginImageContext(rect.size)
self.draw(in: rect)
guard let img = UIGraphicsGetImageFromCurrentImageContext() else {
return nil
}
UIGraphicsEndImageContext()
guard let imageData = img.jpegData(compressionQuality: compressionQuality) else {
return nil
}
print("DEBUG: IMAGE DATA IS (imageData)")
return UIImage(data: imageData)
}

压缩图像就是以较低的质量将图像保存在当前状态,如大小。这导致图像的像素大小相同,但文件大小较小。像素密度"数据"减少或颜色减少会导致质量下降。

在大多数情况下,您已经确定了要显示的图像的大小。尤其适用于网页设计。如果你想节省下载时间和文件大小,你可以选择压缩图像,或者比较将图像保存为jpg和png。每一个都使用不同的开箱即用的压缩算法。

您可以将图像的像素大小缩小。但你会把你的图像拉伸到更大的尺寸,它看起来就不会那么清晰了。

如果你有很多大图像,并且你知道你永远不会按照它们的真实大小使用它们,为了节省空间,你可以把这些图像缩小。

以任何方式更改图像都会对质量产生影响。

UIImageview根据其内容模式属性指定的行为自动缩放和裁剪。

imageView.contentMode = .scaleAspectFit
imageView.image = image

那为什么我们需要调整图像的大小呢?当它大于显示它的图像视图时。假设您有30Mb的图像。要在imageview上显示该图像,首先需要将jpeg解码为位图。这将需要大量的内存使用来适应imageview,而且应用程序对用户来说可能会变得很慢。这就是我们使用图像大小调整的原因。有一种技术。这叫做下采样。因此,重新调整图像大小意味着要缩短图像的分辨率。从而将减小图像大小。

图像压缩是在不影响分辨率的情况下降低图像的文件大小。当然,降低文件大小会影响图像的质量。

最新更新