将图像存储在应用程序

时间:2014-01-13 05:09:45

标签: ios iphone objective-c

我使用以下代码创建了名为“Image store”的文件夹。我的要求是我想在api成功时将图像保存到文件夹“Image store”,图像应该保存在应用程序本身而不是数据库或相册中。我想知道我可以在应用程序中存储图像的机制

-(void) createFolder {

   UIImage *image = [[UIImage alloc]init];

    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/ImageStore"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
    else
    {

    }
}

4 个答案:

答案 0 :(得分:2)

//Make a method that has url (fileName) Param 
NSArray *documentsDirectory =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);

NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];

NSFileManager *fileManager =[NSFileManager defaultManager];

if ([fileManager fileExistsAtPath:textPath])
{
    return YES;
}
else
{
    return NO;
}

UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage
imageNamed:@""]];//Placeholder image


if ([url isKindOfClass:[NSString class]])
{
    imgView.image = [UIImage imageNamed:[url absoluteString]];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
}
else if ([fileManager fileExistsAtPath:url])
{


    NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];

    NSError *error = nil;

    NSData *fileData = [NSData dataWithContentsOfFile:textPath options:NSDataReadingMappedIfSafe error:&error];

    if (error != nil)
    {
        DLog(@"There was an error: %@", [error description]);
        imgView.image=nil;
    }
    else
    {
        imgView.image= [UIImage imageWithData:fileData]
    }
}
else
{   UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
     initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];


    CGPoint center = imgView.center;
    //            center.x = imgView.bounds.size.width / 2;

    spinner.center = center;
    [spinner startAnimating];

    [imgView addSubview:spinner];


    dispatch_queue_t downloadQueue = dispatch_queue_create("iamge downloader", NULL);

    dispatch_async(downloadQueue, ^{

        NSData *imgData = [NSData dataWithContentsOfURL:url];

        dispatch_async(dispatch_get_main_queue(), ^{


            [spinner removeFromSuperview];

            UIImage *image = [UIImage imageWithData:imgData];


             NSError *error = nil;

[imgData writeToFile:url options:NSDataWritingFileProtectionNone error:&error];

if (error != nil)
{

}
else
{

}

            imgView.image = image;
        });
    });
}

如果图像不存在于文档中,那么它会加载一个图像然后保存它,一个活动指示器被添加到显示图像加载保存,

答案 1 :(得分:1)

创建目录

后编写此代码
NSString *path= [documentsDirectory stringByAppendingPathComponent:@"/ImageStore"];
UIImage *rainyImage =[UImage imageNamed:@"rainy.jpg"];
NSData *Data= UIImageJPEGRepresentation(rainyImage,0.0);
[data writeToFile:path atomically:YES]

答案 2 :(得分:1)

你可以做这样的事情 你可以像这样运行一个循环

  //at this point u can get image data
  for(int k = 0 ; k < imageCount; k++)
  {
     [self savePic:[NSString stringWithFormat:@"picName%d",k] withData:imageData];//hear data for each pic u can send
  }


 - (void)savePic:(NSString *)picName withData:(NSData *)imageData
   {
     if(imageData != nil)
     {
      NSString *path = [NSString stringWithFormat:@"/ImageStore/%@.png",pincName];
      NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
      NSString *pngPath = [NSString stringWithFormat:@"%@%@",Dir,path]; //path means ur destination contain's  this format -> "/foldername/picname" pickname must be unique
     if(![[NSFileManager defaultManager] fileExistsAtPath:[pngPath stringByDeletingLastPathComponent]])
     {
         NSError *error;
         [[NSFileManager defaultManager] createDirectoryAtPath:[pngPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:&error];
         if(error)
         {
             NSLog(@"error in creating dir");
         }
     }
     [imageData writeToFile:pngPath atomically:YES];
  }
 }


成功下载并保存后,您可以检索如下图像


- (UIImage *)checkForImageIn:(NSString *)InDestination
  {

    NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *pngPath = [NSString stringWithFormat:@"%@%@",Dir,InDestination];//hear "InDestination" format is like this "/yourFolderName/imagename" as i said imagename must be unique .. :) 


    UIImage *image = [UIImage imageWithContentsOfFile:pngPath];
    if(image)
   {
      return image;
   }
   else
    return nil;
 }


link to find path 看到这个链接找到路径..

aganin像下面这样运行循环

  NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
  for(int k = 0 ; k < imageCount; k++)
    {
       UIImage *image = [self checkForImageIn:[NSString stringWithFormat: @"/yourFolderName/ImageName%d",k]];//get the image 
       [imagesArray addObject:image];//store to use it somewhere ..
    }

答案 3 :(得分:1)

文档目录如下:

// Let's save the file into Document folder. 
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

// If you go to the folder below, you will find those pictures
NSLog(@"%@",docDir);

NSLog(@"saving png");
NSString *pngFilePath = [NSString stringWithFormat:@"%@/test.png",docDir];

这只是提供的代码示例,它告诉您在ipone设备中保存正确路径的位置。

查看下面的博文,这是一步一步的源代码指南。

Download an Image and Save it as PNG or JPEG in iPhone SDK