System.Drawing.Image 流 C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1668469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:51:08  来源:igfitidea点击:

System.Drawing.Image to stream C#

c#c#-3.0

提问by Linda

I have a System.Drawing.Imagein my program. The file is not on the file system it is being held in memory. I need to create a stream from it. How would I go about doing this?

System.Drawing.Image我的程序中有一个。该文件不在其保存在内存中的文件系统上。我需要从中创建一个流。我该怎么做呢?

采纳答案by JaredPar

Try the following:

请尝试以下操作:

public static Stream ToStream(this Image image, ImageFormat format) {
  var stream = new System.IO.MemoryStream();
  image.Save(stream, format);
  stream.Position = 0;
  return stream;
}

Then you can use the following:

然后您可以使用以下内容:

var stream = myImage.ToStream(ImageFormat.Gif);

Replace GIF with whatever format is appropriate for your scenario.

将 GIF 替换为适合您场景的任何格式。

回答by John Gietzen

Use a memory stream

使用内存流

using(MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ...);
    return ms.ToArray();
}