c# - 如何从 SQL Server 获取位图图像并将其显示在 PictureBox 中?
问题描述
当我从 SQL Server DB 获取位图图像以将其显示在 PictureBox 中时,出现异常:
参数无效错误
这是我的代码:
public void FillHotMenu(int key, string connection, string logdir)
{
try
{
SqlConnection conn = new SqlConnection(connectionstr);
conn.Open();
SqlCommand cmd = new SqlCommand("Pm_R_GetHotMenus", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@keyid", key);
SqlDataReader read = cmd.ExecuteReader();
flowLayoutPanel1.Controls.Clear();
while (read.Read())
{
byte[] b = (byte[])(read["KeyBitmap"]);
if (b.Length > 1)
{
PictureBox pic = new PictureBox();
pic.Size = new Size(flowLayoutPanel1.Width / 4, flowLayoutPanel1.Height / 4);
string s = read["KeyBitmap"].ToString();
using (MemoryStream ms = new MemoryStream(b))
{
Bitmap image = new Bitmap(ms); // *** I'm getting error here
pic.Image = image;
}
pic.SizeMode = PictureBoxSizeMode.StretchImage;
flowLayoutPanel1.Controls.Add(pic);
}
else if (read["KeyTextValue"].ToString() != "")
{
textvalue = "";
PictureBox pic = new PictureBox();
pic.Size = new Size(flowLayoutPanel1.Width / 4, flowLayoutPanel1.Height / 4);
textvalue = read["KeyTextValue"].ToString();
pic.Paint += new PaintEventHandler(pictureBox1_Paint);
flowLayoutPanel1.Controls.Add(pic);
}
}
conn.Close();
}
catch (Exception ex)
{
string logstr = ex.InnerException == null ? "" : ex.InnerException.Message;
log.append("ERROR:" + ex.Message + "-->" + logstr, logdirectory);
MessageBox.Show(ex.Message);
Environment.Exit(0);
}
}
我怎么解决这个问题?
编辑:
我已经毫无例外地尝试了这段代码,但 PictureBox 中没有显示任何内容:
var ms = new MemoryStream(b);
ms.Seek(0, SeekOrigin.Begin);
ms.Position = 0;
byte[] imagebytes = ms.ToArray();
Bitmap bitmap = new Bitmap(pic.Width, pic.Height);
bitmap.Save(ms, ImageFormat.Png);
pic.Image = Image.FromStream(ms);
pic.SizeMode = PictureBoxSizeMode.StretchImage;
解决方案
推荐阅读
- javascript - 在 js 数组中仅标记第二个重复的对象
- python - 为每个网球运动员创建新的数据框
- apache-spark - Erro 'DataFrame' 对象没有属性 '_get_object_id'
- java - 如何删除firestore上的文档?
- linq - Enum 上的 EF Core 总和
- java - 从 Docker 连接到 localhost(使用 localstack 模拟 AWS 的 Java 应用程序)
- python - 在 Python 中导入 WindowProporties 时出错
- apache-flink - 在 source 开始时在 flink 中对整个 dataStream 进行分区,并保持分区直到 sink
- python - 使用cppyy时如何在python中创建子类?
- javascript - 使用 Formik 的服务器端验证错误