How to downscale a UIImage in IOS by the Data size

前端 未结 5 840
时光取名叫无心
时光取名叫无心 2020-12-04 16:30

I am looking to downscale a UIImage in iOS.

I have seen other questions below and their approach on how to downscale the image by size. R

5条回答
  •  执笔经年
    2020-12-04 16:40

    -(NSData*)testData
    {
        UIImage *imageToUpload=[UIImage imageNamed:@"images/lifestyle2.jpg"];
        NSData *imgData=UIImageJPEGRepresentation(imageToUpload,1.0);
        float compressionRate=10;
        while (imgData.length>1024)
        {
            if (compressionRate>0.5)
            {
                compressionRate=compressionRate-0.5;
                imgData=UIImageJPEGRepresentation(imageToUpload,compressionRate/10);
            }
            else
            {
                return imgData;
            }
        }
        return imgData;
    }
    

    It maintains image quality not lass than 1MB.

    Call it with,

    NSData *compressedImageData=[self testData];
    NSLog(@"%lu KB",compressedImageData.length);
    

提交回复
热议问题