How to Compress Image but not resize it Using Xamarin IOS?

后端 未结 1 1585
臣服心动
臣服心动 2021-01-15 18:36

I need to upload an image to server which is pretty large around, But i want to keep the Aspect Ratio but compress the size of the file because I am uploading multiple files

相关标签:
1条回答
  • 2021-01-15 19:04

    If you don't want to resize your image, then sending it as JPEG and PNG will make it smaller than just sending the bitmap data. You can get NSData representation of the image in PNG or JPEG. There are some pros/cons to each format, but JPEG allows sacrificing quality for more compression.

    *Assuming you have a UIImage named image.

    using(NSData pngImage = image.AsPNG()){
        byte[] imageBytes = pngImage.ToArray();
        // upload your image data, write to a file, etc.
    }
    
    // AsJPEG compression argument can be 0 to 1
    // 0 is max compression (lowest quality), 1 is best quality
    using(NSData jpgImage = image.AsJPEG(0.0f)){
        byte[] imageBytes = jpgImage.ToArray();
        // upload your image data, write to a file, etc.
    }
    

    You can also use AsJPEG in a loop with decreasing values of compression to try and get the image size below a specific threshold. That might be a little slow though, so you have to weight the benefits for your specific use.

    0 讨论(0)
提交回复
热议问题