将图像保存到 MemoryStream 时遇到困难
我在将图像(在本例中为 jpg)中的字节流保存到 System.IO.MemoryStream 对象时遇到一些困难。目标是将 System.Drawing.Image
保存到 MemoryStream
,然后使用 MemoryStream
将图像写入字节数组(我最终需要将其插入数据库)。但是,在 MemoryStream
关闭后检查变量 data
表明所有字节都为零......我很困惑,不确定我在哪里做错了...
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...
}
任何见解将不胜感激!
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...
}
Any insights will be much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要将数据从流加载到数组中,您需要读取,而不是写入(并且需要倒回)。但是,在本例中更简单的是
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()
:如果目的是将图像字节保存到数据库中,您可以简单地执行以下操作:
然后插入数据库逻辑以保存字节。
If the purpose is to save the image bytes to a database, you could simply do:
And then plug in your database logic to save the bytes.
我几秒钟前发现这篇文章的另一个原因,也许你会发现它有用:
http://www.codeproject.com/KB/recipes/ImageConverter.aspx
基本上我不明白为什么你尝试在具有图像的内存流上写入一个空数组。这是你清理图像的方法吗?
如果不是这种情况,请使用 ToArray 方法读取您在内存流中写入的内容并将其分配给您的字节数组
,仅此而已
I found for another reason this article some seconds ago, maybe you will find it useful:
http://www.codeproject.com/KB/recipes/ImageConverter.aspx
Basically I don't understand why you try to write an empty array over a memory stream that has an image. Is that your way to clean the image?
If that's not the case, read what you have written in your memorystream with ToArray method and assign it to your byte array
And that's all
试试这种方法,它对我有用
我没有使用图像控件,而是使用了面板控件。
Try this way, it works for me
Well instead of a Image control, I used a Panel Control.