UIImageJpgRepresentation doubles image resolution

拈花ヽ惹草 提交于 2019-12-11 08:08:31

问题


I am trying to save an image coming from the iPhone camera to a file. I use the following code:

try UIImageJPEGRepresentation(toWrite, 0.8)?.write(to: tempURL, options: NSData.WritingOptions.atomicWrite)

This results in a file double the resolution of the toWrite UIImage. I confirmed in the watch expressions that creating a new UIImage from UIImageJPEGRepresentation doubles its resolution

-> toWrite.size CGSize  (width = 3264, height = 2448)   
-> UIImage(data: UIImageJPEGRepresentation(toWrite, 0.8)).size  CGSize? (width = 6528, height = 4896)

Any idea why this would happen, and how to avoid it?

Thanks


回答1:


Your initial image has scale factor = 2, but when you init your image from data you will get image with scale factor = 1. Your way to solve it is to control the scale and init the image with scale property:

@available(iOS 6.0, *)
public init?(data: Data, scale: CGFloat)

Playground code that represents the way you can set scale

extension UIImage {

    class func with(color: UIColor, size: CGSize) -> UIImage? {
        let rect = CGRect(origin: .zero, size: size)
        UIGraphicsBeginImageContextWithOptions(size, true, 2.0)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        context.setFillColor(color.cgColor)
        context.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

let image = UIImage.with(color: UIColor.orange, size: CGSize(width: 100, height: 100))
if let image = image {
    let scale = image.scale
    if let data = UIImageJPEGRepresentation(image, 0.8) {
        if let newImage = UIImage(data: data, scale: scale) {
            debugPrint(newImage?.size)
        }
    }
}


来源:https://stackoverflow.com/questions/43704615/uiimagejpgrepresentation-doubles-image-resolution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!