繁体   English   中英

将图片框图像存储到数据库

[英]store the picturebox image to a database

我有一个图片框。 图片框中的图像是 static 之一。 我正在从资源文件夹加载图像。 我无法从图片框中读取 static 图像并将其存储在数据库中。 这是我的代码。

 private void btnOk_Click(object sender, EventArgs e)
    {
        Image votingBackgroundImage = pictureBox5.Image;
        Bitmap votingBackgroundBitmap = new Bitmap(votingBackgroundImage);
         Image votingImage = (Image)votingBackgroundBitmap;
            var maxheight = (votingImage.Height * 3) + 2;
            var maxwidth = votingImage.Width * 2;
            if (maxheight == 227 && maxwidth == 720)
            {

                 System.IO.MemoryStream defaultImageStream = new System.IO.MemoryStream();
                 Bitmap NewImage =new Bitmap(votingImage,new Size(720,227));
                 Image b = (Image)NewImage;
                  b.Save(defaultImageStream, System.Drawing.Imaging.ImageFormat.Bmp);
                 defaultImageData = new byte[defaultImageStream.Length];
              }
    }

我用来在数据库中添加图像的查询:

            String MyString1=string.format("insert into question_table(background_image) Values(@background_image)");
            com = new SqlCommand(MyString1, myConnection);
              com.Parameters.Add("@background_image", SqlDbType.Image).Value = defaultImageData;
                com.ExecuteNonQuery();

当我在 sql 数据库中检查这个时,它将值存储为0 x000000 ...

您只是在创建byte[]但您从未真正复制过内容

尝试

 System.IO.MemoryStream defaultImageStream = new System.IO.MemoryStream();
 Bitmap NewImage =new Bitmap(votingImage,new Size(720,227));
 Image b = (Image)NewImage;
 b.Save(defaultImageStream, System.Drawing.Imaging.ImageFormat.Bmp);
 defaultImageData = new byte[defaultImageStream.Length];
 //assign byte array the content of image
 defaultImageData = defaultImageStream .ToArray();

看起来您正在分配一个字节数组来存储流的内容,但您并没有复制内容本身。

也许您不需要中间数组。 尝试使用MemoryStreamToArray()方法:

b.Save(defaultImageStream, System.Drawing.Imaging.ImageFormat.Bmp);
// ...
com.Parameters.Add("@background_image", SqlDbType.Image).Value
    = defaultImageStream.ToArray();

您必须将其存储为 Blob 即字节数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM