UIImageJPEGRepresentation和UIImagePNGRepresentation的比較

今天做多圖上傳的功能,圖片超大,相機像素太高了,一張照片幾十M,就過來看看壓縮的問題

先給出結論
在讀取圖片數據內容時,建議優先使用UIImageJPEGRepresentation,並可根據自己的實際使用場景,設置壓縮係數,進一步降低圖片數據量大小.

Iphone上有兩種讀取圖片數據的簡單方法: UIImageJPEGRepresentationUIImagePNGRepresentation.

UIImageJPEGRepresentation函數需要兩個參數:圖片的引用和壓縮係數.

UIImagePNGRepresentation只需要圖片引用作爲參數.

通過在實際使用過程中,比較發現:

UIImagePNGRepresentation(UIImage* image) 要比UIImageJPEGRepresentation(UIImage* image, 1.0) 返回的圖片數據量大很多.

譬如,同樣是讀取攝像頭拍攝的同樣景色的照片, UIImagePNGRepresentation()返回的數據量大小爲199K ,而 UIImageJPEGRepresentation(UIImage* image, 1.0)返回的數據量大小隻爲140KB,比前者少了50多KB.

如果對圖片的清晰度要求不高,還可以通過設置 UIImageJPEGRepresentation函數的第二個參數,大幅度降低圖片數據量.

譬如,剛纔拍攝的圖片, 通過調用UIImageJPEGRepresentation(UIImage* image, 1.0)讀取數據時,返回的數據大小爲140KB,但更改壓縮係數後,通過調用UIImageJPEGRepresentation(UIImage* image, 0.5)讀取數據時,返回的數據大小隻有11KB多,大大壓縮了圖片的數據量 ,而且從視角角度看,圖片的質量並沒有明顯的降低.

UIImageJPEGRepresentation and UIImagePNGRepresentation both are slow

-(NSData *)imageConvertToBinary :(UIImage *) image{

        NSLog(@"Image Convert  ");

        //UIImagePNGRepresentation(image);
        NSData *imageData = UIImageJPEGRepresentation(image, .000032);
         NSLog(@"Image Done  ");

        //Change size of image to 10kbs

        int size = imageData.length;
        NSLog(@"SIZE OF IMAGE:First %i ", size);
        NSData *data = UIImageJPEGRepresentation(image, .0032);
        NSLog(@"Start while  ");
        int temp=0;
        while (data.length / 1000 >= 10) {
            image = [UIImage imageWithImage:image andWidth:image.size.width/2 andHeight:image.size.height/2];

            data = UIImageJPEGRepresentation(image, .0032);
            temp++;
            NSLog(@"temp  %u",temp);

        }

        size = data.length;
        NSLog(@"SIZE OF IMAGE:after %i ", size);


        return data;

    }

and also i have category class on UIImage
@implementation UIImage (ImageProcessing)

+(UIImage*)imageWithImage:(UIImage*)image andWidth:(CGFloat)width andHeight:(CGFloat)height
{
    UIGraphicsBeginImageContext( CGSizeMake(width, height));
    [image drawInRect:CGRectMake(0,0,width,height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}
@end

解決辦法:

- (NSData *)imageConvertToBinary :(UIImage *) image{
    NSData *data ;
    NSLog(@"Start while  ");
    int temp=0;
    while (data.length / 1000 >= 10) {
        image = [UIImage imageWithImage:image andWidth:image.size.width/2 andHeight:image.size.height/2];
        data = UIImageJPEGRepresentation(image, .0032);
        temp++;
        NSLog(@"temp  %u",temp);
    }
    NSLog(@"End while  ");
    int size = data.length;
    NSLog(@"SIZE OF IMAGE:after %i ", size);
    return data;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章