首页 > 解决方案 > 为什么 jpegData 不保存我调整大小的图像?更新

问题描述

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

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

            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)

当我检索“更新”图像时,它具有原始大小。您看不到这一点,但图像肯定已被替换。

显然我错过了一些基本的东西——请让我摆脱痛苦。

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

一个 (4032 3024)

乙 (200 150)

C (200 150)

D (400 300)

因此,正在发生的事情是将大小翻倍——而不是像我之前认为的那样——没有更新新的大小。

这是否使它更清晰或更令人困惑?

谈到谜题,我得到了-1,但没有人说为什么。

标签: swiftuiimage

解决方案


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)

推荐阅读