Difficulty Saving Image To MemoryStream(难以将图像保存到 MemoryStream)
问题描述
我在将字节流从图像(在本例中为 jpg)保存到 System.IO.MemoryStream
对象时遇到了一些困难.目标是将System.Drawing.Image
保存到MemoryStream
,然后使用MemoryStream
将图像写入字节数组(我最终需要将它插入到数据库中).但是,在 MemoryStream
关闭后检查变量 data
表明所有字节都为零......我很困惑,不确定我做错了什么...
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:难以将图像保存到 MemoryStream


基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01