【问题标题】:Save an image in its respective format to a stream将图像以各自的格式保存到流中
【发布时间】:2011-11-22 01:04:45
【问题描述】:

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

这涉及一个简单的调整大小功能,我对此没有任何问题。

它涉及读取原始图像格式,这段代码似乎可以工作:

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

【问题讨论】:

标签: c# image-processing system.drawing


【解决方案1】:

这是我使用的,虽然我没有测试过透明度。这使图像保持其原始格式,而无需打开原始格式。您可能默认使用 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 上使用透明度对其进行了测试,它确实保留了它。我将把它归档(直到现在,我只将它用于 jpegs。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    相关资源
    最近更新 更多