Compress bitmap with GZipStream
<p>I`m trying to compress a bitmap image but the output stream is always empty.</p>

<p>Does anyone know what i am doing wrong?</p>

<p>Thanks in advance!</p>

<pre><code>public static byte[] CompressBitmap (Bitmap img)
    {
        using (MemoryStream outputStream = new MemoryStream ())
        {
            // Compress image
            using (GZipStream zipStream = new GZipStream (outputStream, CompressionMode.Compress))
            {
                // Convert image into memory stream and compress
                using (MemoryStream imgStream = new MemoryStream ())
                {
                    img.Save (imgStream, System.Drawing.Imaging.ImageFormat.Bmp);                                                        
                    imgStream.CopyTo (zipStream);
                    return outputStream.ToArray ();
                }
            }
        }
    }
</code></pre>

<p>I changed a little bit and seems like its working:</p>

<pre><code>public static byte[] CompressBitmap (Bitmap img)
    {
        // Convertendo bitmap para memory stream
        using (MemoryStream inStream = new MemoryStream ())
        {
            // Para evitar memory leak
            using (img) 
            {
                img.Save(inStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }

            // Salva stream no array de byte
            byte[] buffer = new byte[inStream.Length];
            inStream.Read (buffer, 0, buffer.Length);

            // Comprime bitmap
            using (MemoryStream outStream = new MemoryStream())
            {
                using (GZipStream gzipStream = new GZipStream(outStream, CompressionMode.Compress))
                {
                    gzipStream.Write(buffer, 0, buffer.Length);
                    return outStream.ToArray();
                }
            }
        }            
    }
</code></pre>

<p>But now, the decompress is wrong:</p>

<pre><code>public static Bitmap DecompressBitmap (byte[] compressed)
    {
        try
        {
            using (MemoryStream inputStream = new MemoryStream (compressed))
            {
                using (GZipStream zipStream = new GZipStream (inputStream, CompressionMode.Decompress))
                {
                    // Decompress image and convert to bitmap
                    using (MemoryStream outputStream = new MemoryStream ())
                    {
                        zipStream.CopyTo (outputStream);
                        return (Bitmap)Bitmap.FromStream (zipStream);
                    }
                }
            }
        }
        catch (Exception ex)
        {

        }

        return null;
    }
</code></pre>
