为什么 jpegData 不保存我调整大小的图像?更新

Why is jpegData not saving my resized image? UPDATED

我正在从相机或照片库中拍摄照片并将其保存在我的应用程序中。我不需要这么大的图像,所以我使用扩展来缩小它。然后我将它保存到应用程序 space。但是缩小的尺寸没有保存。

我已经尝试了各种关于大小更改、删除和保存的排列。

            let path = "/var/mobile/Containers/Data/Application/0595DE63-AE43-4DCF-9BD0-FB552844ECF5/Documents/tour15/H25.jpg"
            print("A",hotspotImage.image!.size)
            hotspotImage.image = hotspotImage.image!.resizeImage(2048, opaque: true)
            print("B",hotspotImage.image!.size)
            let fileManager  = FileManager.default
            try! fileManager.removeItem(atPath: path)
            try! hotspotImage.image!.jpegData(compressionQuality: 0.8)!.write(to: URL(fileURLWithPath: path), options: [.atomic])
            print("C",hotspotImage.image!.size)
            let  imageTest = UIImage(contentsOfFile: path)
            print("D",imageTest!.size)

结果是...

A (4032.0, 3024.0)

B (2048.0, 1536.0)

C (2048.0, 1536.0)

D (4096.0, 3072.0)

当我检索 "updated" 图像时,它具有原始大小。你看不到这个,但图像肯定被替换了。

显然我遗漏了一些基本的东西 - 请让我摆脱痛苦。

向之前回复的好心人致歉 - 但我现在发现了一些额外的重要信息。示例大小愚弄了我们所有人。当我将缩小后的尺寸更改为 200(而不是原始尺寸的一半)时,我得到以下结果:

A (4032 3024)

B (200 150)

C (200 150)

D (400 300)

所以发生的事情是将大小加倍 - 而不是 - 正如我之前认为的那样 - 没有更新为新大小。

这会使它更清晰还是更像一个谜题?

说到谜题,我得到了 -1,但没有人说出原因。

UIImage(named:) 缓存图像。您第二次调用它时不是从磁盘读取(我猜您之前在某个地方用相同的路径调用过它)。要绕过缓存,您需要使用 init(contentsOfFile:)

以下应按预期工作:

let path = getAppFolder() + photoUrl
print("A",hotspotImage.image!.size)
hotspotImage.image = hotspotImage.image!.resizeImage(2048, opaque: true)
print("B",hotspotImage.image!.size)
let fileManager  = FileManager.default
try! fileManager.removeItem(atPath: path)
try! hotspotImage.image!.jpegData(compressionQuality: 0.8)!.write(to: URL(fileURLWithPath: path), options: [.atomic])
print("C",hotspotImage.image!.size)
let  imageTest = UIImage(contentsOfFile: path)
print("D",imageTest!.size)

如果它自动将所需大小加倍,则听起来好像正在应用屏幕缩放。我会检查正在使用的扩展。如果缩放设置为 0.0,则将应用当前屏幕缩放。

屏幕缩放非常适合显示在屏幕上的图像。 (这就是它被称为屏幕缩放的原因。)但是创建一个目标不是屏幕的图像,缩放应该设置为 1.0 以保持所需的大小并且 NOT 两倍或三倍。

我最近 运行 遇到了类似的问题。我正在使用

调整图像大小
func resizeImage(toSize: CGSize) -> UIImage? {
    guard let cgImg = cgImage else { return nil }
    let scale = cgImg.size().aspectFitScale(toSize)
    let newImage = UIImage.init(cgImage: cgImg, scale: 1/scale, orientation: imageOrientation)
    return newImage
}

保存的pngData和jpegData是原图,没有任何缩放。为了看到任何调整大小,我必须通过创建一个新的 CGImage 来调整大小。

func resizeImage_other(toSize: CGSize) -> UIImage? {
    let scaleByWidth = toSize.width / size.width
    let scaleByHeight = toSize.height / size.height
    
    let finalScale = CGFloat.minimum(scaleByWidth, scaleByHeight)
    let newHeight = size.height * finalScale
    let newWidth = size.width * finalScale
    UIGraphicsBeginImageContext(CGSize.init(width:newWidth, height:newHeight))
    draw(in: CGRect.init(x:0, y:0, width:newWidth, height:newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return newImage
}