我正在尝试将来自iPhone相机的图像保存到文件中。我使用以下代码:
try UIImageJPEGRepresentation(toWrite, 0.8)?.write(to: tempURL, options: NSData.WritingOptions.atomicWrite)
这会导致文件加倍toWrite UIImage的分辨率。我在表达式中确认从UIImageJPEGRepresentation创建一个新的UIImage会使其分辨率加倍
-> toWrite.size CGSize (width = 3264, height = 2448)
-> UIImage(data: UIImageJPEGRepresentation(toWrite, 0.8)).size CGSize? (width = 6528, height = 4896)
知道为什么会这样,以及如何避免它?
由于
答案 0 :(得分:1)
您的初始图像的比例因子= 2,但是当您从数据初始化图像时,您将获得比例因子= 1的图像。您解决它的方法是控制比例并使用scale属性初始化图像:
@available(iOS 6.0, *)
public init?(data: Data, scale: CGFloat)
表示您可以设置比例的方式的游乐场代码
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)
}
}
}