将图像从GIF转换为JPEG

时间:2019-12-18 11:09:29

标签: c# jpeg

我必须将GIF转换为JPEG。我必须将字节保存到图像,然后重新打开并将其转换为JPEG。我尝试使用两个流来更改类型,但出现错误“ GDI +中发生一般错误”。有什么解释吗?

    public static byte[] GetJpegBytes(byte[] bytes)
    {
        using (var stream = new MemoryStream(bytes))
        {
            var temporaryImage = $"{Path.Combine(System.Web.HttpRuntime.AppDomainAppPath, Guid.NewGuid().ToString())}.jpeg";
            var image = Image.FromStream(stream);

            image.Save(temporaryImage, ImageFormat.Jpeg);
            using (var memoryStream = new FileStream(temporaryImage, FileMode.Open))
            {
                byte[] byteRsult = new byte[memoryStream.Length];
                memoryStream.Read(byteRsult, 0, (int)memoryStream.Length);
                memoryStream.Close();
                File.Delete(temporaryImage);
                return byteRsult;
            }
        }

    } 

3 个答案:

答案 0 :(得分:0)

如果您不想使用流,可以尝试以下操作:

Bitmap bitmap = new Bitmap("C:\MyFile.jpg");

bitmap.Save("C:\MyNewFile.gif", ImageFormat.Gif);

答案 1 :(得分:0)

您可以使用此扩展名转换格式图像 我使用这个简单的扩展名来转换流。

public static Stream ConvertImage(this Stream originalStream, ImageFormat format)
{
          var image = Image.FromStream(originalStream);

               using(var stream = new MemoryStream())
           {
                image.Save(stream, format);
                stream.Position = 0;
                return stream;
           }
    }

用法:

var outputStream = stream.ConvertImage(ImageFormat.Png);

答案 2 :(得分:0)

当我以另一种格式重新保存图像时,我发现了同样的问题。创建新图像并将旧图像绘制到该图像上似乎可以解决问题。

public static byte[] GetJpegBytes(byte[] bytes)
{
    using (var stream = new MemoryStream(bytes))
    using (var image = Image.FromStream(stream))
    using (var targetImage = GetImage(image, image.Width, image.Height))
    using (var targetStream = new MemoryStream())
    {
        targetImage.Save(targetStream, ImageFormat.Jpeg);
        return targetStream.ToArray();
    }
}

private static Bitmap GetImage(Image source, int width, int height)
{
    using (var image = new Bitmap(width, height))
    using (var g = Graphics.FromImage(image))
    {
        //if the gif is transparent we want the jpg to have white background.
        g.Clear(Color.White); 

        //Make it pretty
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;

        //Draw the old image
        g.DrawImage(source, 0, 0, width, height);

        return image;
    }
}