开发者

Compress bitmap before sending over network

I'm trying to send a bitmap screenshot over network, so I need to compress it before s开发者_如何学编程ending it. Is there a library or method for doing this?


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.


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);


Try the System.IO.DeflateStream class.


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;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜