2013-03-18 63 views
1

我用下面的代碼保存我的形象---如何獲取本地保存的UIImage路徑到UIImage?

#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] 


NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0]; 
NSString *caldate = [now description]; 


NSString *filePath= [NSString stringWithFormat:@"%@/%@.jpg", DOCUMENTS_FOLDER,caldate]; 
imageurl = [NSURL fileURLWithPath:filePath]; 
dataImage = UIImagePNGRepresentation(myimage); 
[dataImage writeToFile:filePath atomically:YES]; 

IMAGEURL是打印類似下面

文件://本地主機/用戶/ varmab /庫/ Application%20Support/iPhone%20Simulator/6.1 /應用/ E2EDF729-4684-465B-8BE3-2C0ACFA2EC03 /文檔/ 2013年3月18日2012%:02:31%20 + 0000.jpg

現在,我想展示保存的圖像,即圖像是st或運算在上面的文件路徑

我想下面的代碼:

//1st process: 
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageurl]]; 

//2nd process: 
NSURL *urlString =imageurl; 
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:urlString]])]; 
UIImage *image = [UIImage imageWithData:imageData]; 

//3rd process: 
NSData * imageData = [[NSData alloc] initWithContentsOfURL:imageurl ]; 
self.testingImageView.image = [UIImage imageWithData: imageData]; 

請指引我,我在做什麼錯誤?

+0

請參閱本http://stackoverflow.com/questions/7440662/how-to-get-all-paths-for-files-in-documents-directory – Vinodh 2013-03-18 13:49:35

+0

使用的NSFileManager – Rushabh 2013-03-18 13:49:40

+0

我不喜歡這一點,但,我得到null ------- NSString * path = [[NSBundle mainBundle] pathForResource:@「images」ofType:@「jpeg」]; imgUlr = [NSURL URLWithString:path]; NSLog(@「********* testingImg is%@」,imgUlr); @Rushabh – Babul 2013-03-18 13:51:24

回答

4

你爲什麼不直接使用此方法:

- (id)initWithContentsOfFile:(NSString *)path 

正是在UIImage類已經上市。

[self.testingImageView setImage: [[UIImage alloc] initWithContentsOfURL:imageurl]]; 

試試這個,讓我知道如果你再次面臨同樣的問題。

注意:請檢查圖片url是否與保存該圖片時獲取的較舊圖片相似。

+0

我越來越,而不是initWithContentsOfURL,我越來越initWithContentsOfFile – Babul 2013-03-18 13:57:26

+0

爲什麼我指的是這種方法,因爲它會減少你的代碼行。如果你對此感到滿意,那麼你能否接受並提出答案? – Mrunal 2013-03-18 14:28:49

0

這將爲您提供文檔目錄下所有文件的路徑;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 

     NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil]; 

     NSLog(@"files array %@", filePathsArray); 

您可以使用下面的代碼獲取filePathsArray中每個對象的路徑;文檔目錄,店面形象出現,並從同一位置的

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[filePathsArray objectAtIndex:0]]; 
0

斯威夫特
獲取路徑,你可以檢索。

func getDocumentsDirectory() -> URL { 
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) 
    let documentsDirectory = paths[0] 
    return documentsDirectory 
} 

if let image = UIImage(named: "example.png") { 
    if let data = UIImagePNGRepresentation() { 
     let filename = getDocumentsDirectory().appendingPathComponent("copy.png") 
     try? data.write(to: filename) 
    } 
}