[英]How to load image to UIImage from file without extension
I have a resources downloaded at the runtime. 我在运行时下载了资源。 Images reside in some sub folder in the "caches" directory.
图像位于“缓存”目录中的某些子文件夹中。
How can I load image to UIImage when I know the path to the file, image is "PNG" type, but it doesn't have extension? 当我知道文件的路径,图像是“ PNG”类型,但没有扩展名时,如何将图像加载到UIImage?
I could not see any constructor of UIImage which takes type of the file as argument, so I reckon that it could be tricky one 我看不到任何以文件类型为参数的UIImage构造函数,因此我认为它可能很棘手
No this is not that hard, just load the data first. 不,这并不难,只需先加载数据即可。 Here the
cacheURL
is a NSURL
to the file. 这里的
cacheURL
是文件的NSURL
。
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:cacheURL options:NSDataReadingMapped error:&error];
Now you can check if the file could be loaded: 现在,您可以检查文件是否可以加载:
if (data) {
image = [UIImage imageWithData:data];
}
Code is in Objective-C because I just copied from an old project, but should easy to convert to Swift. 代码是在Objective-C中的,因为我只是从一个旧项目复制而来,但是应该很容易转换为Swift。
Since your file is already downloaded 由于您的文件已下载
let path = "theFilePath"
if let data = NSData(contentsOfFile: path) {
let image = UIImage(data: data as Data)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.