UIImageJpgRepresentation使图像分辨率翻倍 [英] UIImageJpgRepresentation doubles image resolution

查看:328
本文介绍了UIImageJpgRepresentation使图像分辨率翻倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将来自iPhone相机的图像保存到文件中.我使用以下代码:

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)

这导致文件的分辨率是toWrite UIImage的两倍.我在手表表达式中确认,从UIImageJPEGRepresentation创建新的UIImage会使分辨率提高一倍

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?

谢谢

推荐答案

您的初始图像的比例因子= 2,但是从数据初始化图像时,您将获得比例因子= 1的图像.控制比例并使用scale属性初始化图像:

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

这篇关于UIImageJpgRepresentation使图像分辨率翻倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆