search

Home  >  Q&A  >  body text

iOS图片加载(imageData)

微信和微博分享的对于原生封装的加载图片的方法如下:

+ (NSData )loadImageDataWithImageUrl:(NSString )urlString {

NSURL *url = [NSURL URLWithString:urlString];
SDImageCache *imageCache = [SDImageCache sharedImageCache];
UIImage *image = nil;
NSData *imageData = nil;
//有缓存,从缓存中去图片

if ([imageCache imageFromMemoryCacheForKey:urlString]) {

image = [imageCache imageFromMemoryCacheForKey:urlString];

imageData = UIImageJPEGRepresentation(image, 1.0);

}else if ([imageCache imageFromDiskCacheForKey:urlString]) {

image = [imageCache imageFromDiskCacheForKey:urlString];

imageData = UIImageJPEGRepresentation(image, 1.0);

}else{

//缓存中没有图片去下载
imageData = [NSData dataWithContentsOfURL:url];
}
return imageData;
}

现在 : imageData = [NSData dataWithContentsOfURL:url]; 这句代码的效率极低,导致分享会很慢,现在求优化方法,望各位大神指点!

高洛峰高洛峰2890 days ago363

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-04-18 09:32:25

    Didn’t you write: There is no download in the cache... everything is downloaded. It must be very slow using this basic method.
    I don’t quite understand, since SDWebImage is used, why do we need to write another method to loadImageData


    Supplement

    Download the image UIImage and then convert it into data
    Isn’t your cache the same thing as taking out the image and converting it into data?

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:32:25

    @Curiousity If it is not in the cache, download it. Is there a better method than imageData = [NSData dataWithContentsOfURL:url]; ? I have looked at SDWebImage, but there is no way to download imageData directly!

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:32:25

    Try this asynchronous
    SDWebImageDownloader.h

    - (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url
                                             options:(SDWebImageDownloaderOptions)options
                                            progress:(SDWebImageDownloaderProgressBlock)progressBlock
                                           completed:(SDWebImageDownloaderCompletedBlock)completedBlock;
    

    reply
    0
  • Cancelreply