如何以编程方式压缩图像

时间:2010-07-08 12:01:40

标签: objective-c cocoa-touch iphone

我正在接收来自xml feed的图像,它们的大小非常大,如何在将它们显示在table-cell中之前压缩它们。

我的代码是

   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];
如果可以的话,请帮帮我.....

2 个答案:

答案 0 :(得分:1)

我有这个缩放图像的实用工具方法:

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

    return newImage;
}

像这样使用:

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我不能为我的生活记住我从哪里得到它但是它在过去很好地服务于我

答案 1 :(得分:0)

简单易用: -

-(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;}