C# 将picturebox图像存储到数据库
我有一个画框。图片框中的图像是静态图像。我正在从资源文件夹加载图像。我无法从图片框中读取静态图像并将其存储在数据库中。这是我的密码C# 将picturebox图像存储到数据库,c#,sql,picturebox,C#,Sql,Picturebox,我有一个画框。图片框中的图像是静态图像。我正在从资源文件夹加载图像。我无法从图片框中读取静态图像并将其存储在数据库中。这是我的密码 private void btnOk_Click(object sender, EventArgs e) { Image votingBackgroundImage = pictureBox5.Image; Bitmap votingBackgroundBitmap = new Bitmap(votingBackground
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…看起来您正在分配一个字节数组来存储流的内容,但您不会复制内容本身 也许您不需要中间数组。尝试使用
MemoryStream
的方法:
b.Save(defaultImageStream, System.Drawing.Imaging.ImageFormat.Bmp);
// ...
com.Parameters.Add("@background_image", SqlDbType.Image).Value
= defaultImageStream.ToArray();
您只是创建了
字节[]
,但实际上从未复制过内容
试一试
必须将其存储为Blob,即字节数组
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();