UIImage在caches目录中设置image withfile

时间:2014-09-05 11:36:04

标签: ios7 uiimageview uiimage

当我尝试从本地文件路径(Caches目录)设置图像时,我得到nil图像 文件:/// ......

NSString* localImagePath=@"file:///Users/mac/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/BD2135B6-5E03-4797-960E-B6C2BF2D6958/Library/Caches/myImage.jpeg"
[[UIImage alloc]initWithContentsOfFile:localImagePath]; 

我搜索了很多问题,但却找不到合适的方法。

2 个答案:

答案 0 :(得分:0)

- (IBAction)saveImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
UIImage *image = imageView.image; // imageView is my image from camera
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];   
}

答案 1 :(得分:0)

问题可能是url编码所以我通过获取缓存目录路径来解决这个问题

   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
   NSString *cacheDirectory = [paths objectAtIndex:0];
   NSString *localImagePath = [cacheDirectory stringByAppendingPathComponent:@"myImage.jpeg"];
   [[UIImage alloc]initWithContentsOfFile:localImagePath];