首页 > 解决方案 > 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!

    }

}

标签: iosswiftnsdatapixelphoto

解决方案


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)


推荐阅读