无法保存图像到的MemoryStream [英] Difficulty Saving Image To MemoryStream
问题描述
我有一个 System.IO.MemoryStream
目标有些难度从图像保存的字节流(在这种情况下,JPG格式)。我们的目标是要保存为System.Drawing.Image
到的MemoryStream
,然后用的MemoryStream
来将图像写入字节数组(我最终需要将其插入到数据库)。然而,检查变量数据
的的MemoryStream
关闭显示,所有字节都是零后...我敢住了,不知道从哪里我做错了...
I'm having some difficulty saving a stream of bytes from an image (in this case, a jpg) to a System.IO.MemoryStream
object. The goal is to save the System.Drawing.Image
to a MemoryStream
, and then use the MemoryStream
to write the image to an array of bytes (I ultimately need to insert it into a database). However, inspecting the variable data
after the MemoryStream
is closed shows that all of the bytes are zero... I'm pretty stumped and not sure where I'm doing wrong...
using (Image image = Image.FromFile(filename))
{
byte[] data;
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
data = new byte[m.Length];
m.Write(data, 0, data.Length);
}
// Inspecting data here shows the array to be filled with zeros...
}
任何见解将非常感激!
推荐答案
要加载从数据流进一个数组,你的阅读的,不是的写的(你将需要倒带)。但是,更简单地在这种情况下, ToArray的()
:使用
To load data from a stream into an array, you read, not write (and you would need to rewind). But, more simply in this case, ToArray()
:
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
data = m.ToArray();
}
这篇关于无法保存图像到的MemoryStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!