SDWebImage resizing/scaling/cropping images coming from url before caching them

Sukhrob picture Sukhrob · Aug 31, 2012 · Viewed 16.2k times · Source

How can I resize, scale and crop images coming from url before caching them. I tried to achieve this with the following code.

[cell.profilePicture setImageWithURL:[NSURL URLWithString:[rowData objectForKey:@"pictureUrl"]] placeholderImage:nil];
cell.profilePicture.image = [self imageByScalingAndCroppingForSize:CGSizeMake(cell.profilePicture.frame.size.width, cell.profilePicture.frame.size.height) image:cell.profilePicture.image];

This produced a strange result. First, it shows a not resized/scaled/cropped version. But, when I scroll down and then go back, it shows a resized/scaled/cropped version. I know that this code first caches images and resizes/scales/crops them. But, I could not come up with a better solution. I think there should be something that enables to do downloading images so as to resize/scale/crop and caching independently. Any ideas?

Thank you.

Answer

Sukhrob picture Sukhrob · Sep 2, 2012

I figured out the solution on my own.

Instead of

[cell.profilePicture setImageWithURL:[NSURL URLWithString:[rowData objectForKey:@"pictureUrl"]] placeholderImage:nil];

which downloads and caches images automatically, use this

SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:url delegate:self options:0 success:^(UIImage *image) 
{
    cell.profilePicture.image = [self imageByScalingAndCroppingForSize:CGSizeMake(cell.profilePicture.frame.size.width, cell.profilePicture.frame.size.height) image:image];
} failure:nil];

Don't forget to include

#import <SDWebImage/UIImageView+WebCache.h>
@interface YourViewController : UIViewController <SDWebImageManagerDelegate>