2017-08-04 35 views
1

我想壓縮UIImage。但是,我收到了錯誤的尺寸。 我敢肯定UIImageJPEGRepresentation是wrong.how修復 對不起我的英語不好UIImageJPEGRepresentation得到錯誤的大小

+ (NSData *)compressDataWithImg:(UIImage *)originalImage compression:(CGFloat)compression size:(CGFloat)size { 
    NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(originalImage, compression)]; 
    if ((data.length/1024.0) > size) 
    { 
     compression = compression - 0.1; 
     if (compression > 0) { 
      return [[self class] compressDataWithImg:originalImage compression:compression size:(CGFloat)size]; 
     }else{ 
      return data; 
     } 
    }else{ 
     return data; 
    } 
    return data; 
} 

    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
    UIImage *fullImage = info[UIImagePickerControllerOriginalImage]; 
    fullImage = [fullImage fixOrientationToUp]; 

    UIImage *imgData = [fullImage scaleToSizeWithLimit:0]; 
    NSData *data = [Util compressDataWithImg:imgData compression:0.9 size:256]; // this is right:size:2M 
    UIImage *image = [UIImage imageWithData:data];//i use this UIImage 

    NSData *xxx = [NSData dataWithData: UIImageJPEGRepresentation(image,1) ];// wrong size:7~8M WHY?... 

    if (self.imageSelectBlock) { 
     self.imageSelectBlock(image); 
    } 

    [picker dismissViewControllerAnimated:YES completion:NULL] ; 
} 

感謝幫助我

回答

0

我發現,當我一次又一次地使用UIImageJPEGRepresentationimageWithData處理一個圖像。圖像數據的length逐漸增加。

測試代碼:

UIImage *image = [UIImage imageNamed:@"test.png"]; 

NSLog(@"first: %lu", UIImageJPEGRepresentation(image, 1.0).length); 
NSLog(@"second: %lu", UIImageJPEGRepresentation([UIImage imageWithData:UIImageJPEGRepresentation(image, 1.0)], 1.0).length); 
NSLog(@"third: %lu", UIImageJPEGRepresentation([UIImage imageWithData:UIImageJPEGRepresentation([UIImage imageWithData:UIImageJPEGRepresentation(image, 1.0)], 1.0)], 1.0).length); 

日誌:

first: 361586 
second: 385696 
third: 403978 

我覺得這個問題是由UIImageJPEGRepresentation造成的。

只是一個測試。

而且我發現一個相關的問題:

When i am using UIImagePNGRepresentation or UIImageJPEGRepresentation for converting UIImage into NSdata, the image size is too much increased