Compress size of image to 250kb using xamarin.forms without dependency service

后端 未结 2 1576
逝去的感伤
逝去的感伤 2021-01-02 14:41

I\'m trying to compress image taken from camera to 250kb size in Xamarin.Forms. I found ways to do that in dependency service but I want it without dependency service (pure

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-02 15:31

    It is a very complicated job since you would need a ton of knowledge about image processing.

    Most importantly, re-inventing wheel is a bad move.

    http://www.codeproject.com/Articles/83225/A-Simple-JPEG-Encoder-in-C

    Take a look of the above code project which only tackles JPEG; not to say TIFF, GIF, BMP etc.

    Image compression involves many complex mathematics transforms, like DCT and Huffman.

    You will need a whole university semester to learn those basics.


    On the other hand, wisely utilizing platform support, you can complete the task within a minute.

    BitmapEncoder in Windows Phone.

    FileStream stream = new FileStream("new.jpg", FileMode.Create);
    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
    encoder.QualityLevel = 30;
    encoder.Frames.Add(BitmapFrame.Create(image));
    encoder.Save(stream);
    

    Bitmap in Android

    using (System.IO.Stream stream = System.IO.File.Create(targetFile))
    {
        bitmap.Compress(Bitmap.CompressFormat.Jpeg, 30, stream);
    }
    

    UIImage in iOS

    NSData data = image.AsJPEG(0.3);
    

    Bitmap in .NET framework

    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
    ImageCodecInfo codec = codecs.First(t => t.FormatID == ImageFormat.Jpeg.Guid);
    EncoderParameters parameters = new EncoderParameters(1);
    parameters.Param[0] = new EncoderParameter(Encoder.Quality, 30L);
    bitmap.Save("output.jpg", codec, parameters);
    

提交回复
热议问题