C# 将图像以其各自的格式保存到流中

C# 将图像以其各自的格式保存到流中,c#,image-processing,system.drawing,C#,Image Processing,System.drawing,我有一个挑战,涉及多个部分,其中大部分我没有问题。我需要一个函数来读取图像流,自动将其调整到指定大小,将图像压缩到特定级别(如果适用),然后返回图像流,但同时保持原始图像格式并保持透明度(如果有) 这涉及到一个简单的调整大小功能,我没有问题 它涉及读取原始图像格式,此代码似乎有效: // Detect image format if (newImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg)) { //etc

我有一个挑战,涉及多个部分,其中大部分我没有问题。我需要一个函数来读取图像流,自动将其调整到指定大小,将图像压缩到特定级别(如果适用),然后返回图像流,但同时保持原始图像格式并保持透明度(如果有)

这涉及到一个简单的调整大小功能,我没有问题

它涉及读取原始图像格式,此代码似乎有效:

// Detect image format
if (newImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
{
      //etc for other formats
}
//etc
返回图像流是我遇到的难题。我可以返回压缩后的流,但它默认为Jpeg。我看不出在哪里指定格式。当我通过保存两次图像来指定格式时,我就失去了透明度

我想有两个问题:

1) 如果我调整图像的大小,是否还需要在PNG上重建alpha透明度? 2) 如何在必要时以各自的格式保存到内存流,同时保持透明度

这是我的密码

System.Drawing.Imaging.ImageCodecInfo[] Info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
System.Drawing.Imaging.EncoderParameters Params = new System.Drawing.Imaging.EncoderParameters(1);
long ImgComp = 80;
Params.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImgComp);

MemoryStream m_s = new MemoryStream();
// Detect image format
if (newImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
{
    newBMP.Save(m_s, ImageFormat.Jpeg);
}
else if (newImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
{
    newBMP.Save(m_s, ImageFormat.Png);
}

// Save the new graphic file to the server

newBMP.Save(m_s, Info[1], Params);
retArr = m_s.ToArray();

这就是我使用的,尽管我还没有测试过透明度。这将使图像保持其原始格式,而无需打开原始格式。您默认使用jpeg的原因可能是
newImage.RawFormat
作为格式的guid返回,但不是实际的枚举值:

    using (Bitmap newBmp = new Bitmap(size.Width, size.Height))
    {
        using (Graphics canvas = Graphics.FromImage(newBmp))
        {
            canvas.SmoothingMode = SmoothingMode.HighQuality;
            canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
            canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
            canvas.DrawImage(newImage, new Rectangle(new Point(0, 0), size));
            using (var stream = new FileStream(newLocation, FileMode.Create))
            {
                // keep image in existing format
                var newFormat = newImage.RawFormat;
                var encoder = GetEncoder(newFormat);
                var parameters = new EncoderParameters(1);
                parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);

                newBmp.Save(stream, encoder, parameters);
                stream.Flush();
            }
        }
    }
编辑


我只是在png上用透明度测试了一下,它确实保留了它。我会将其归档到“好知道”(到目前为止,我只在JPEG中使用过它。)

这看起来很有趣,因为在调整大小时会丢失透明度: