我尝试在保存到数据库后将图像保存在字节数组中, 但
imagebyteArray
返回 (int)
。
我逐行检查了所有代码,一切都很好,没有错误,但是当将照片保存到数据库中时,我定义为字节的变量返回值(int),并且照片显示为不存在转换字节。
这是我的代码:
Byte[] imagebyteArray;
// forimage
Image temp = new Bitmap(pictureBox1.Image);
MemoryStream ms = new MemoryStream();
temp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
imagebyteArray = ms.ToArray();
Hashtable ht = new Hashtable();
ht.Add("@id", id);
ht.Add("@Name", Textpname.Text);
ht.Add("@price", textprice.Text);
ht.Add("@cat", Convert.ToInt32(coCategory.SelectedValue));
ht.Add("@img", imagebyteArray);
这将打开对话框:
private void btnBrows_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "image(.jpg, .png)|*.png;*jpg";
if (ofd.ShowDialog() == DialogResult.OK)
{
FilePath = ofd.FileName;
PictureBox.Image = new Bitmap(FilePath);
}
}
}
这是在 SQL Server 中存储图像的代码:
string qry = "";
if (id == 0)//وارد کردن
{
qry = "insert into Product values(@Name, @price, @img, @cat)";
}
else//بروز کردن
{
qry = "Update Product set pName = @Name, pPrice = @price, CategoryID = @cat, pImage = @img where PID = @id";
}
要更新已存储在数据库中的产品:
private void ForUpdateLoade()
{
string qry = @"select * from Product where PID = @id";
using (SqlCommand cmd = new SqlCommand(qry, Mainclass.con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Textpname.Text = dt.Rows[0]["pName"].ToString();
textprice.Text = dt.Rows[0]["pPrice"].ToString();
Byte[] imageArray = (byte[])(dt.Rows[0]["pImage"]);
byte[] imagebyteArray = imageArray;
pictureBox1.Image = Image.FromStream(new MemoryStream(imageArray));
}
}
}
在 INSERT 上指定目标列
qry = "insert into Product values(@Name, @price, @img, @cat)";
应该是
qry = "insert into Product(pName,pPrice,pImage,CategoryID) values(@Name, @price, @img, @cat)";