Search code examples
iosswiftuiimagejpegrepresentation

UIImageJpgRepresentation doubles image resolution


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


Solution

  • 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)
            }
        }
    }