gpt4 book ai didi

ios - 为什么当我减少图片中的像素数量时,文件的大小会变大?

转载 作者:行者123 更新时间:2023-11-28 10:37:33 26 4
gpt4 key购买 nike

我正在尝试使用 swift 调整图像大小。我一直在尝试将像素宽度设置为 1080p。我使用的原始照片宽度为 1200p,文件大小为 760 KB。使用以下函数将图像调整为 1080p 后,结果为 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!
}

完整代码如下

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!

}

}

最佳答案

无法确定,但您在转换后的图像上指定了 compressionQuality: 1.0,所以可能原始文件是以不同的质量:大小比率保存的? (即,由于压缩算法的性质,以低质量保存的较大图像很容易导致比以高质量保存的较小图像更小的文件大小)

关于ios - 为什么当我减少图片中的像素数量时,文件的大小会变大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52614130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com