开发者

System.Drawing.Image to stream C#

开发者 https://www.devze.com 2022-12-10 07:25 出处:网络
I have a System.Drawing.Image in 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?Try the

I have a System.Drawing.Image in 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?


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.


Use a memory stream

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


public static Stream ToStream(this Image image)
{
     var stream = new MemoryStream();

     image.Save(stream, image.RawFormat);
     stream.Position = 0;

     return stream;
 }


Using File Stream

 public Stream ToStream(string imagePath)
    {
    Stream stream=new FileStream(imagePath,FileMode.Open);
    return stream;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消