下载时UIImage被破坏

时间:2013-09-12 10:27:43

标签: iphone ios objective-c ipad uiimage

我开发了iOS应用程序,我从服务器下载图像并将其保存在我的文档目录中。

但我面临的问题是,即使服务器响应成功,有时我的图片在下载时也会损坏。

这是我的代码段,

urlFile是服务器上的UIImage路径,例如:www.abcd.com/images/pqr.jpg

我用于在我的DocDirectory中保存图片名称的文件名。

- (void)downloadFile:(NSString *)urlFile withName:(NSString *)fileName 
{
    NSString *trimmedString = [urlFile stringByTrimmingCharactersInSet:
                               [NSCharacterSet whitespaceAndNewlineCharacterSet]];

    NSLog(@"trimmedString=%@",trimmedString);
    if ([trimmedString length]>0)
    {
        HTTPEaterResponse *response = [HTTPEater get:[NSString stringWithFormat:@"%@",trimmedString]];

    if ([response isSuccessful])
        {  
           NSLog(@"isSuccessful");
            [self saveImage:[[UIImage alloc] initWithData:[response body]] withName:fileName];
        } else {
            NSLog(@"Url response failed %@", [response description]);
        }
    }

}


    - (void)saveImage:(UIImage *)image withName:(NSString *)name
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        NSData *data = UIImagePNGRepresentation(image);
        NSLog(@"image =%@",image);

        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
        [fileManager createFileAtPath:fullPath contents:data attributes:nil];

    }

当我看到我的日志时,显示:

  • trimmedString = www.abcd.com/images/pqr.jpg
  • isSuccessful
  • image = null

提前致谢。

5 个答案:

答案 0 :(得分:2)

我使用以下代码,它适用于我。

NSData *thumbImageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:ImageURL]];
[thumbImageData writeToFile:cachedThumbnailFileName atomically:YES];
UIImage * image =  [UIImage imageWithContentsOfFile:cachedThumbnailFileName];
imageView.image = image;

希望它对你有所帮助。 :)

答案 1 :(得分:1)

要在目录使用上保存图像:

NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
[UIImagePNGRepresentation(selectedImage) writeToFile:pngPath atomically:YES];
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];  
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

答案 2 :(得分:0)

您是否记录了回复[response body]

尝试将该回复转换为NSData,然后另存为图片。 使用Base64Encoding类,您可以将响应转换为base64Data

NSData *imageData = [NSString base64DataFromString:[response body]];
[self saveImage:[[UIImage alloc] initWithData:imageData] withName:fileName];

答案 3 :(得分:0)

而你可以使用“NSURLRequest”和“NSURLConnection” 例如,如果你获得图像URL,那么

    NSURL* aURL = [NSURL URLWithString:trimmedString];//get the url of string
    NSURLRequest *aReq = [NSURLRequest requestWithURL:aURL];
    NSURLConnection *aConnection = [NSURLConnection connectionWithRequest:aReq delegate:self]; //get a connection to url , since it confirms to delegate u need to implement delegate methods 
    if(aConnection == nil) //if it is nil then cancel and close the request
    { 
       aConnection = nil;  
      [aConnection cancel];
    }


   // after this implement this delegate methods
  - (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)received_data
  {
      if(image_data == nil)    //if data is not initialised initialise it
      {
          image_data = [[NSMutableData alloc]init];
      }

      [self.image_data appendData:received_data];//append the received data

  }
  //this method is called after successful download of the image
  - (void)connectionDidFinishLoading:(NSURLConnection *)connection;
 {
    // UIImage* sampleImage = [UIImage imageWithData:self.image_data];
    // self.image = sampleImage; //convert the data to image 
    //since u hav complete downloaded date in "self.image_data"

    NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];//set the name of the image and path may it saving in application directory check it out  
    [self.image_data writeToFile:imagePath atomically:YES]; //saving the data with name
 }

希望这有助于你:)

答案 4 :(得分:0)

我建议使用SDWebimage Class SDWebimage下载..我认为它对你很有帮助,即使我总是喜欢SDWebimage Library。这是一些事情。

An UIImageView category adding web image and cache management to the Cocoa Touch framework
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
Animated GIF support
WebP format support
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked
Performances!
Use GCD and ARC