我正在尝试将来自iPhone摄像机的图像保存到文件。我使用以下代码:
try UIImageJPEGRepresentation(toWrite, 0.8)?.write(to: tempURL, options: NSData.WritingOptions.atomicWrite)
这导致文件将towrite uiimage的分辨率加倍。我在手表的表达中确认,从uiimagejpegresentation创建新的UIImage使其分辨率翻了一番
-> toWrite.size CGSize (width = 3264, height = 2448)
-> UIImage(data: UIImageJPEGRepresentation(toWrite, 0.8)).size CGSize? (width = 6528, height = 4896)
知道为什么会发生这种情况以及如何避免这种情况?
谢谢
您的初始图像具有比例因子= 2,但是当您从数据启动图像时,您将获得比例因子= 1的图像具有比例属性的图像:
@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)
}
}
}