Search code examples
iossdwebimage

How to load images using SDWebImage library


Hi I am using SDWebImage for loading images ok that's fine

Here I am getting images from services and I want to resize those images and I want to load them using SDWebImage

for this I wrote the code below

Obj.imageYH---> this is imageURL

  NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:Obj.imageYH]];

    UIImage *actualImage = [UIImage imageWithData:imageData];
    UIGraphicsBeginImageContext(CGSizeMake(150, 150));
    [actualImage drawInRect:CGRectMake(0,0,150, 150)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *smallData = UIImagePNGRepresentation(newImage);

    NSString *Finalstring = [[NSString alloc] initWithData:smallData encoding:NSUTF8StringEncoding] ;


    [Mainimage sd_setImageWithURL:[NSURL URLWithString: Finalstring] placeholderImage:[UIImage imageNamed:@"collectionViewIcon.png"]];

but in the code above, I am getting null value in Finalstring. How can I resize it and how can I load images using SDWebImage?


Solution

  • Use below line of codes instead of your code :

    UIImage *actualImage = [UIImage imageWithData:imageData];
    UIGraphicsBeginImageContext(CGSizeMake(150, 150));
    [actualImage drawInRect:CGRectMake(0,0,150, 150)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *smallData = UIImagePNGRepresentation(newImage);
    
    [smallData writeToFile:Finalstring atomically:YES];// Finalstring is file path of resize image 
    
    [Mainimage sd_setImageWithURL:[NSURL URLWithString: Finalstring] placeholderImage:[UIImage imageNamed:@"collectionViewIcon.png"]];