我对如何UIImageJPEGRepresentation
与 Documents 目录中的文件路径相关感到完全困惑。
基本上,当我从文件路径中删除文件,然后调用UIImageJPEGRepresentation
aUIImage
时,它返回 nil,但如果文件路径没有被删除,则UIImageJPEGRepresentation
返回图像的数据表示。
这是我的示例代码来演示我的意思:
func functionA()
{
if imagePaths_ARRAY.isEmpty == false
{
for pathToDelete in imagePaths_ARRAY
{
if fileManager.fileExists(atPath: pathToDelete)
{
do
{
try fileManager.removeItem(atPath: pathToDelete)
}
catch let error as NSError
{
print(error.localizedDescription)
}
}
else
{
print("ERROR")
}
}
imagePaths_ARRAY.removeAll()
}
print(images_ARRAY)
for image in images_ARRAY
{
print(image)
if let imageData = UIImageJPEGRepresentation(image, 0.5)
{
print("RETURN GOOD")
let imageName = getImageName()
let imagePath = getDirectoryPath().appending("/" + imageName)
let success = fileManager.createFile(atPath: imagePath, contents: imageData, attributes: nil)
if success == true
{
imagePaths_ARRAY.append(imagePath)
}
}
else
{
print("RETURN NIL")
}
}
}
第一次被functionA
调用,imagePaths_ARRAY
是空的,所以内部代码块不执行。UIImages
我循环遍历每个图像的数组,然后调用UIImageJPEGRepresentation
将其转换为Data
要写入文件的对象,然后将其添加imagePath
到imagePaths_ARRAY
数组中以在代码的其他地方使用。
对于每个图像,我都会看到一个日志,RETURN GOOD
并且所有图像都被写入文件。
但是,当functionA
被称为SECOND的时候,imagePaths_ARRAY
不是空的,所以我从imagePaths_ARRAY
.
但是当再次UIImageJPEGRepresentation
调用image
时,它返回nil?
我完全不知道为什么,因为每个image
inimages_ARRAY
都给了我一个有效的UIImage
:
[<UIImage: 0x600000085280> size {4288, 2848} orientation 0 scale 1.000000]
如第一句话所述,我想知道如何使用removeItem
原因删除文件UIImageJPEGRepresentation
以返回 nil?
更新:当我替换UIImageJPEGRepresentation
为时UIImagePNGRepresentation
,图像被压缩得很好。我完全糊涂了!