2011-09-13 44 views
2

我想要在文檔目錄文件夾中獲取圖像。未在文檔目錄文件夾中獲取圖像

我正在使用此代碼。

NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 

    for(int i=0;i<[imagepath count];i++) 
    { 
    NSString* documentsDirectory = [path objectAtIndex:0]; 

    NSURL *img = [NSURL URLWithString:[imagepath objectAtIndex:i]]; 

    //here imagepath is array in that i get the url of image. 
    //here when i print the img data i got url from where i have to get images. 


    NSData *data = [NSData dataWithContentsOfURL:img options:NSDataReadingMapped error:nil]; 

    //here when i put NSLog i get the null. 

    NSString *fullImagePath1 = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"image%d.png",i]]; 

[newreturnImage addObject:fullImagePath1]; 

[data writeToFile:fullImagePath1 options:NSDataWritingAtomic error:nil]; 
} 

我無法在文檔目錄文件夾中獲取圖像。

這段代碼有什麼問題?

回答

3

試試這個代碼,

NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES); 
    NSString *docDirectory = [sysPaths objectAtIndex:0]; 
    NSString *filePath = [NSString stringWithFormat:@"%@/%@", docDirectory,@"myimage.png"]; 
    UIImage *cellImage=[UIImage imageWithContentsOfFile:filePath]; 
    UIImageView *temp=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)]; 
    temp.image=cellImage; 
    [myView addSubview:temp]; 
    [temp release]; 

更新時間:

NSData *myData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myURL]]; 
UIImage *myImage = [[UIImage alloc] initWithData:myData]; 
+0

我從url獲取圖像,我必須轉換該圖像,以便我必須採取NSData。 –

+0

所以你需要從一個URL獲取圖像,你不能實現它? – booleanBoy

+0

在我的代碼nsusrl * img中提到,我得到的網址,但在nsdata中獲得空值。 –

1

此鏈接可以幫助你。在鏈接詹姆斯韋伯斯特提供了一個很好的方法,適合您的要求。如果這對你沒有幫助。下面的代碼肯定會適合你,因爲它適合我。

How save images in home directory?

NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 

    for(int i=0;i<[imagepath count];i++) 
    { 
    NSString* documentsDirectory = [path objectAtIndex:0]; 

    NSURL *img = [NSURL URLWithString:[imagepath objectAtIndex:i]]; 

    NSData *imageData = [[NSData alloc] initWithContentsOfURL:img]; 

    NSString *fullImagePath1 = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"image%d.png",i]]; 

[newreturnImage addObject:fullImagePath1]; 

[data writeToFile:fullImagePath1 options:NSDataWritingAtomic error:nil]; 
} 

希望這有助於你。

謝謝。

+0

無論如何..這可能會幫助別人,如果不是你。 –

相關問題