Nauman.Khattak
Nauman.Khattak

Reputation: 641

how to compress image programmatically

I am receiving images from xml feed they are very large in size how can i compress them before displaying them in table-cell.

my code is

   int blogEntryIndex1 = [indexPath indexAtPosition: [indexPath length] -1];
    imgstring=[[blogEntries objectAtIndex: blogEntryIndex1] objectForKey: @"image"];
NSURL *url = [NSURL URLWithString:imgstring];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *img = [[UIImage alloc] initWithData:data];
cell.imageView.image=[img autorelease];

please help me if you can.....

Upvotes: 0

Views: 1635

Answers (2)

Abhimanyu Daspan
Abhimanyu Daspan

Reputation: 1125

Simple to use:-

-(UIImage *)fireYourImageForCompression:(UIImage *)imgComing{

NSData *dataImgBefore   = [[NSData alloc] initWithData:UIImageJPEGRepresentation((imgComing), 1.0)];//.1 BEFORE COMPRESSION
int imageSizeBefore     = (int)dataImgBefore.length;


NSLog(@"SIZE OF IMAGE: %i ", imageSizeBefore);
NSLog(@"SIZE OF IMAGE in Kb: %i ", imageSizeBefore/1024);



NSData *dataCompressedImage = UIImageJPEGRepresentation(imgComing, .1); //.1 is low quality
int sizeCompressedImage     = (int)dataCompressedImage.length;
NSLog(@"SIZE AFTER COMPRESSION  OF IMAGE: %i ", sizeCompressedImage);
NSLog(@"SIZE AFTER COMPRESSION OF IMAGE in Kb: %i ", sizeCompressedImage/1024); //AFTER

//now change your image from compressed data
imgComing = [UIImage imageWithData:dataCompressedImage];


return imgComing;}

Upvotes: 0

deanWombourne
deanWombourne

Reputation: 38485

I've got this utility method that will scale an image :

- (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

Use it like this :

int blogEntryIndex1 = [indexPath indexAtPosition: [indexPath length] -1];
imgstring=[[blogEntries objectAtIndex: blogEntryIndex1] objectForKey: @"image"];
NSURL *url = [NSURL URLWithString:imgstring];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [self imageWithImage:[UIImage imageWithData:data] scaledToSize:CGSizeMake(20, 20)]; // Scale it to 20x20px
cell.imageView.image=[img autorelease];

NB I can't for the life of me remember where I got it from but it's served me well in the past

Upvotes: 1

Related Questions