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

时间:2018-10-02 18:17:10

标签: ios swift nsdata pixel photo

我正在尝试使用swift调整图像大小。我一直在尝试将像素宽度的数量设置为1080p。 Im使用的原始照片的宽度为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!

    }

}

1 个答案:

答案 0 :(得分:3)

不能肯定地说,但是您要在转换后的图像上指定compressionQuality: 1.0,因此可能以不同的quality:size比例保存了原始图像吗? (即,由于压缩算法的特性,以低质量保存的较大图像可以比以高质量保存的较小图像更容易产生较小的文件大小)