UIImage 在下载时损坏

Posted

技术标签:

【中文标题】UIImage 在下载时损坏【英文标题】:UIImage gets corrupted while Downloading 【发布时间】:2013-09-12 10:27:42 【问题描述】:

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

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

这是我的代码 sn-p,

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 成功了 图像=null

提前致谢。

【问题讨论】:

【参考方案1】:

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

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

希望对您有所帮助。 :)

【讨论】:

【参考方案2】:

要将图像保存到目录使用:

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

【讨论】:

selectedImage 是什么?【参考方案3】:

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

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

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

【讨论】:

显示错误:不知道选择器base64DataFromString:的类方法 使用这个答案***.com/a/800976/1160493 其中包含base64DataFromString 方法。【参考方案4】:

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

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

【讨论】:

【参考方案5】:

你可以使用“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
 

希望对你有帮助:)

【讨论】:

如何为下载的图片命名?? 也可以看到这个答案***.com/questions/6238139/…

以上是关于UIImage 在下载时损坏的主要内容,如果未能解决你的问题,请参考以下文章

将大 UIImage 比例下载到 UIImageView

UIImage 在将其转换为 CIImage,然后转换为 CGImage 并返回 UIImage 时失去其方向

我可以在保存之前检查下载的图像是不是损坏吗?

UIActivityViewController 在共享我编辑的 UIImage 时崩溃,但适用于 UIImage(named:)

在运行时更改 UIImage 渲染模式

iOS_UIImage的方向(imageOrientation)