ios - why is it that when I decrease the number of pixels in a picture the size of the file gets larger?
问题描述
I am trying to resize an image using swift. I have been trying to set the number of pixels width to 1080p. The original photo Im using has 1200p width and is a 760 KB file. After resizing the image with the following function to have 1080p the result is 833 KB.
func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
let scale = newWidth / image.size.width
let newHeight = image.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
Below is the code in its entirety
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var image:UIImage!
override func viewDidLoad() {
super.viewDidLoad()
image = imageView.image
let bcf = ByteCountFormatter()
bcf.allowedUnits = [.useKB] // optional: restricts the units to MB only
bcf.countStyle = .file
var string = bcf.string(fromByteCount: Int64(image.jpegData(compressionQuality: 1.0)!.count))
print("formatted result: \(string)")
compressionLabel.text = string
print("Image Pixels: \(CGSize(width: image.size.width*image.scale, height: image.size.height*image.scale))")
image = resizeImage(image: image, newWidth: 1080)
string = bcf.string(fromByteCount: Int64(image.jpegData(compressionQuality: 1.0)!.count))
print("formatted result: \(string)")
compressionLabel.text = string
print("Image Pixels: \(CGSize(width: image.size.width*image.scale, height: image.size.height*image.scale))")
}
func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
let scale = newWidth / image.size.width
let newHeight = image.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
解决方案
Impossible to say for sure, but you are specifying compressionQuality: 1.0
on your converted image, so possibly the original was saved with a different quality:size ratio? (i.e. a larger image saved at low-quality can easily result in a smaller file size than a smaller image saved at high-quality, due to the nature of the compression algorithm)
推荐阅读
- mysql - Julia:如何连接到我的 AWS MySQL 数据库?
- python-3.x - DiscordPy 重写 ~ 用 Persentage 投票
- java - 处理 @OnetoOne 映射时的 Modelmapper 问题
- ruby-on-rails - Rails 委托类型迁移
- javascript - 您好,我想在 Windows 和 Mac 中为 Web 应用程序中的同一页面实现不同的 css 字体。谁能提供我如何实现这一目标
- python - 使用 Python 将处理后的图像上传到 Azure blob
- node.js - 如何避免 jbpm 中的抢先式身份验证错误?
- python - ModuleNotFoundError:没有名为“psycopg2._psycopg”的模块
- java - Class的Spring clear属性值有@Async方法
- android - Jetpack Compose 中的视觉导航图表示?