2010-07-08 25 views
0

我正在從xml接收圖像,它們尺寸非常大,我如何在將它們顯示在表格單元格中之前進行壓縮。如何以編程方式壓縮圖像

我的代碼是

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]; 

請幫助我,如果你能.....

+0

倒不如從源頭上壓縮他們 - 當你將它發送到手機時,你已經支付了流量。 – 2010-07-08 12:09:40

+0

圖片來自網站通過RSS源 – 2010-07-08 12:10:33

回答

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]; 

注:我不能爲我的生活還記得我來自哪裏得到它,但它使我受益匪淺,在過去

+0

請告訴我如何打電話給細胞方法 – 2010-07-08 13:09:59

+0

我打電話給上述方法像這樣.... CGSize itemSize = CGSizeMake(20,40); \t \t .... [self imageWithImage:img scaledToSize:itemSize]; – 2010-07-08 13:19:22

+0

但它不起作用 – 2010-07-08 13:20:26

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;} 
相關問題