美文网首页
UIImageJPEGRepresentation和UIImag

UIImageJPEGRepresentation和UIImag

作者: GitArtOS | 来源:发表于2021-03-17 16:21 被阅读0次

今天做多图上传的功能,图片超大,相机像素太高了,一张照片几十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;
}

相关文章

网友评论

      本文标题:UIImageJPEGRepresentation和UIImag

      本文链接:https://www.haomeiwen.com/subject/fvrecltx.html