[英]How to retrieve Image from MySQL database using C#
我正在尝试使用 function 命令在表单加载时检索图像,但它没有加载并且我收到错误“参数无效”。 请检查我在代码中的错误之处,因为我试图通过断点调试我的代码,它向我显示代码工作正常,但某处图像未从数据库检索到图片框。
这是我的代码:
public static Bitmap ByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
return bm;
}
使用Photoload
function 检索图像:
public void photoLoad()
{
ConnectionDB cnn = new ConnectionDB();
string query1 = "select image from doctor_image where do='" + DoctorPanel.drUsername + "'";
try
{
cnn.Open();
MySqlDataReader row;
row = cnn.ExecuteReader(query1);
while (row.Read())
{
ImageByte = (Byte[])(row["image"]);
}
if (ImageByte != null)
{
// You need to convert it in bitmap to display the image
pictureBox1.Image = ByteToImage(ImageByte);
pictureBox1.Refresh();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
插入数据库
private void Button6_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
// image filters
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == DialogResult.OK)
{
// display image in picture box
//pictureBox1.Image = new Bitmap(open.FileName);
pictureBox1.Image = Image.FromFile(open.FileName);
ConnectionDB cnn = new ConnectionDB();
cnn.Open();
string sql = "INSERT INTO doctor_image(image, do) VALUES('" + pictureBox1.Image + "','" + DoctorPanel.drUsername + "')";
int noofrows = cnn.ExecuteNonQuery(sql);
if (noofrows != -1)
{
MessageBox.Show("Photo uploaded");
}
else
{
MessageBox.Show("Data insert error");
}
}
}
这行代码是错误的:
string sql = "INSERT INTO doctor_image(image, do) VALUES('" + pictureBox1.Image + "','" + DoctorPanel.drUsername + "')";
首先,您使用字符串连接来构建 SQL。 这是安全问题的常见来源(特别是 SQL 注入)。 改用参数。
其次, "'" + pictureBox1.Image + "','"
将简单地将 output 一个类似于'System.Drawing.Bitmap'
的字符串插入到您的数据库中。 这显然不是一个有效的图像,这就是为什么当您尝试加载它时会出现“参数无效”异常的原因。
看起来您只想将图像的字节插入到数据库中,这有一个简单的修复。 您甚至不需要使用Image
class; 只需读取文件的字节并将它们加载到表中:
using (var cmd = new MySqlCommand(@"INSERT INTO doctor_image(image, do) VALUES(@image, @do);", cnn)
{
cmd.Parameters.AddWithValue("@image", File.ReadAllBytes(open.FileName));
cmd.Parameters.AddWithValue("@do", DoctorPanel.drUsername);
cmd.ExecuteNonQuery();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.