我正在尝试压缩位图图像,但输出流始终为空。
有谁知道我做错了什么?
提前致谢!
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 ();
}
}
}
}
我改变了一点,似乎它的工作:
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();
}
}
}
}
但是现在,解压错了:
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;
}