【问题标题】:UIImage gets corrupted while DownloadingUIImage 在下载时损坏
【发布时间】: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

提前致谢。

【问题讨论】:

    标签: iphone ios objective-c ipad uiimage


    【解决方案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];
      

      【讨论】:

      【解决方案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
         }
        

        希望对你有帮助:)

        【讨论】:

        猜你喜欢
        • 2015-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-15
        • 1970-01-01
        • 2017-08-05
        相关资源
        最近更新 更多