代码之家  ›  专栏  ›  技术社区  ›  TheRedCamaro3.0 3.0

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

  •  0
  • TheRedCamaro3.0 3.0  · 技术社区  · 7 年前

    我正在尝试使用swift调整图像的大小。我一直在尝试将像素宽度设置为1080p。我使用的原始照片的宽度为1200像素,是一个760 KB的文件。使用以下函数调整图像大小以获得1080p后,结果为833kb。

        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 回复  |  直到 7 年前
        1
  •  3
  •   jlew    7 年前

    不可能确定,但你在说明 compressionQuality: 1.0 在转换后的图像上,原始图像可能以不同的质量:大小比保存?(即,由于压缩算法的性质,与高质量保存的较小图像相比,低质量保存的较大图像很容易导致较小的文件大小)