首页 > 解决方案 > 如何从 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;

标签: c#bitmap

解决方案


推荐阅读