image compression by size - iPhone SDK

后端 未结 7 1107
北海茫月
北海茫月 2020-11-30 19:56

I would like to compress images (camera/photo library) and then send it to the server. I know I can compress by height and width, but I would like to compress the images by

7条回答
  •  爱一瞬间的悲伤
    2020-11-30 20:44

    Heres some example code that will attempt to compress an image for you so that it doesn't exceed either a max compression or maximum file size

    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    int maxFileSize = 250*1024;
    
    NSData *imageData = UIImageJPEGRepresentation(yourImage, compression);
    
    while ([imageData length] > maxFileSize && compression > maxCompression)
    {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(yourImage, compression);
    }
    

提交回复
热议问题