【问题标题】:Why doesnt UIImage(data:) create an image at the compressed file size?为什么 UIImage(data:) 不以压缩文件大小创建图像?
【发布时间】:2018-10-02 20:07:26
【问题描述】:

在将 UIImage 转换为压缩的 JPEG 表示并返回 UIImage 后,我正在尝试使用以下代码缩小图像的大小,但 UIImage 文件仍然很大,如何缩小 UIImage 的文件大小?

func changeFileSize()->UIImage{
        var needToCompress:Bool = true
        var compressingValue:CGFloat = 1.0
        let bcf = ByteCountFormatter()
        while needToCompress && compressingValue > 0.0{
            let data =  image.jpegData(compressionQuality: compressingValue)!

            if data.count < 1024 * 100{
                needToCompress = false
                image = UIImage(data: data)
                bcf.allowedUnits = [.useKB] // optional: restricts the units to MB only
                bcf.countStyle = .file
                var  newImage = UIImage(data: data)

               let string = bcf.string(fromByteCount: Int64(newImage!.jpegData(compressionQuality: compressingValue)!.count))
                print("Image Pixels: \(CGSize(width: newImage!.size.width*newImage!.scale, height: newImage!.size.height*newImage!.scale))")
                print("final formatted result to be returned: \(string)")
                print("New comrpession value: \(compressingValue)")
                return UIImage(data:  (newImage?.jpegData(compressionQuality: compressingValue))!)!
                break
            }
            else{
                compressingValue -= 0.1
                bcf.allowedUnits = [.useKB] // optional: restricts the units to MB only
                bcf.countStyle = .file
                let string = bcf.string(fromByteCount: Int64(image.jpegData(compressionQuality: compressingValue)!.count))
                print("formatted result: \(string)")
                print("New comrpession value: \(compressingValue)")
            }
        }

        bcf.allowedUnits = [.useKB] // optional: restricts the units to MB only
        bcf.countStyle = .file
        let 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))")
return image
        }

【问题讨论】:

    标签: ios swift uiimage nsdata uiimagejpegrepresentation


    【解决方案1】:

    没有压缩的 UIImage 这样的东西。这就是 UIImage 的全部point。 UIImage 是实际绘制图像的位图——你可能认为它是图像的实际像素。 JPEG 数据只是数据,并且使用压缩。但要将其转换为 UIImage,我们必须解压缩数据并导出像素。

    【讨论】:

    • 如果您对此感到困惑,您可以对此进行一些研究。 2018 年的 WWDC 视频正是关于这个主题的精彩视频。
    猜你喜欢
    • 2013-09-11
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 2014-09-12
    • 2018-08-01
    • 1970-01-01
    相关资源
    最近更新 更多