没有在文档目录文件夹中获取图像

时间:2011-09-13 06:00:26

标签: iphone objective-c cocoa-touch ios4

我想在文档目录文件夹中获取图像。

我正在使用此代码。

  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];
 }

我无法在文档目录文件夹中获取图像。

这段代码有什么问题?

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分:1)

此链接可能对您有所帮助。在链接中 James Webster 提供了一种非常适合您需求的方法。如果这对你没有帮助。下面的代码肯定对你有用,因为它对我有用。

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];
 }

希望这会对你有所帮助。

感谢。