2

I'm trying to send a bitmap screenshot over network, so I need to compress it before sending it. Is there a library or method for doing this?

Josh Withee
  • 9,922
  • 3
  • 44
  • 62
seddik
  • 219
  • 2
  • 5
  • 12

4 Answers4

3

When you save an Image to a stream, you have to select a format. Almost all bitmap formats (bmp, gif, jpg, png) use 1 or more forms of compression. So just select an appropriate format, and make make sure that sender and receiver agree on it.

H H
  • 263,252
  • 30
  • 330
  • 514
2

If you are looking for something to compress the image in quality, here it is-

    private Image GetCompressedBitmap(Bitmap bmp, long quality)
    {
        using (var mss = new MemoryStream())
        {
            EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            ImageCodecInfo imageCodec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(o => o.FormatID == ImageFormat.Jpeg.Guid);
            EncoderParameters parameters = new EncoderParameters(1);
            parameters.Param[0] = qualityParam;
            bmp.Save(mss, imageCodec, parameters);
            return Image.FromStream(mss);
        }
    }

Use it -

var compressedBmp = GetCompressedBitmap(myBmp, 60L);
Ariful Islam
  • 664
  • 8
  • 12
1

Try the System.IO.DeflateStream class.

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
0

May be you can use:

private Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 
        int options = 100;
        while ( baos.toByteArray().length / 1024>100) { // 
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 
            options -= 10;// 10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 
        return bitmap;
    }
mshwf
  • 7,009
  • 12
  • 59
  • 133