2009-06-20 39 views
10

Tôi muốn tải hình ảnh đến UIImageView từ thư viện tài liệu ứng dụng của mình. Tôi đang cố gắng sử dụng mã sau nhưng nó không hoạt động.tải hình ảnh từ thư mục tài liệu trong iPhone

UIImageView *background = [[[UIImageView alloc] initWithFrame:CGRectMake(3, 10, 48, 36)] autorelease]; 

[background setImage:[[UIImage imageAtPath:[[NSBundle mainBundle] pathForResource:@"Thumbnail-small" ofType:@"jpg" inDirectory:@"/Users/nbojja/Library/Application Support/iPhone Simulator/User/Applications/60C2E4EC-2FE0-4579-9F86-08CCF078216D/Documents/eb43ac64-8807-4250-8349-4b1f5ddd7d0d/9286371c-564f-40b4-99bd-a2aceb00a6d3/9"]]] retain]]; 

ai đó có thể giúp tôi thực hiện việc này. nhờ ...

+1

Tại sao không chỉ cần sử dụng imageNamed trên UIImage? – Grouchal

Trả lời

0

Tôi nghĩ rằng những gì bạn thực sự cần là:

UIImage *img = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"myimagefile" ofType:@"png"]]; 
[self.testView.imgView setImage:img]; 
+0

Giải pháp này hoạt động –

-4

Sử dụng [UIImage imageNamed:@"ThumbnailSmall.jpg"];

Điều này sẽ tải lên những gì bạn muốn tôi nghĩ.

26

Nếu bạn thực sự muốn tải một hình ảnh từ thư mục tài liệu của ứng dụng, bạn có thể sử dụng này:

NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docDirectory = [sysPaths objectAtIndex:0]; 
NSString *filePath = [NSString stringWithFormat:@"%@/Thumbnail-small.jpg", docDirectory]; 
background.image = [[[UIImage alloc] initWithContentsOfFile:filePath] autorelease]; 

Tuy nhiên, như đã chỉ ra bởi những người khác ở đây, có thể bạn muốn tải nó từ ứng dụng của bạn bó, trong trường hợp một trong những sẽ làm việc:

background.image = [UIImage imageNamed:@"Thumbnail-small.jpg"]; 

hoặc

NSString *path = [[NSBundle mainBundle] pathForResource:@"Thumbnail-small" ofType:@"jpg"]; 
background.image = [UIImage imageWithContentsOfFile:path]; 
4
NSString *docPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0]; 
NSString *filePath=[NSString stringWithFormat:@"%@/image.png",docPath]; 

BOOL fileExists=[[NSFileManager defaultManager] fileExistsAtPath:filePath]; 

if (!fileExists) 
    NSLog(@"File Not Found"); 
else 
    image = [UIImage imageWithContentsOfFile:filePath]; 
0

Swift 3:

let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory 
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask 
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) 
if let dirPath = paths.first { 
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Image2.png") 
let image = UIImage(contentsOfFile: imageURL.path) 
// Do whatever you want with the image 
} 
Các vấn đề liên quan