swift - 为什么 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,但没有人说为什么。
解决方案
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)
推荐阅读
- c - 如何为字符串数组创建指针?
- javascript - 无法读取对象数组上未定义的属性“推送”
- c# - c# 中是否有在整个集合上调用接口方法的快捷方式?
- java - Do-while 循环不会在 switch-case 语句之后循环
- javascript - javascript调用函数然后销毁函数输出
- android - apk 是否包含有效负载,或者如果我想通过 apk 文件共享我的应用程序,我是否必须添加它们?
- google-apps-script - 如何从一个 Google Sheet Tab 复制/粘贴到另一个 google sheet 并在目标 google sheet 中指定标签?
- vue.js - 从 S3 下载图片:没有“Access-Control-Allow-Origin”标头
- python - 如何从字典创建一个 sqlite3 表
- apache-kafka - 具有特定 avro 服务的 Kafka 聚合给出 NullPointerException