简体   繁体   中英

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?

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

No this is not that hard, just load the data first. Here the cacheURL is a NSURL to the file.

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.

Since your file is already downloaded

let path = "theFilePath"
if let data = NSData(contentsOfFile: path)  {
    let image = UIImage(data: data as Data)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM