简体   繁体   English

如何使用 C# 从 MySQL 数据库中检索图像

[英]How to retrieve Image from MySQL database using C#

I am trying to retrieve an image on Form load using function command but it does not load and I get an error "Parameter is not valid".我正在尝试使用 function 命令在表单加载时检索图像,但它没有加载并且我收到错误“参数无效”。 Please check where I am wrong in the code because I tried to debug my code via break points and it is showing me that code is working fine, but somewhere image is not retrieved from database to picture box.请检查我在代码中的错误之处,因为我试图通过断点调试我的代码,它向我显示代码工作正常,但某处图像未从数据库检索到图片框。

Here is my code:这是我的代码:

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;
}

Retrieve image using Photoload function:使用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);
        }
}

Insert into database插入数据库

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");
            }
        }
}

This line of code is wrong:这行代码是错误的:

string sql = "INSERT INTO doctor_image(image, do) VALUES('" + pictureBox1.Image + "','" + DoctorPanel.drUsername + "')";

Firstly, you're using string concatenation to build the SQL.首先,您使用字符串连接来构建 SQL。 This is a common source of security problems (specifically, SQL injection).这是安全问题的常见来源(特别是 SQL 注入)。 Use parameters instead.改用参数。

Secondly, "'" + pictureBox1.Image + "','" will simply output a string similar to 'System.Drawing.Bitmap' which will be inserted into your database.其次, "'" + pictureBox1.Image + "','"将简单地将 output 一个类似于'System.Drawing.Bitmap'的字符串插入到您的数据库中。 This is obviously not a valid image, which is why you get the "Parameter is not valid" exception when you try to load it.这显然不是一个有效的图像,这就是为什么当您尝试加载它时会出现“参数无效”异常的原因。

It looks like you just want to insert the bytes of the image into your database, which has a simple fix.看起来您只想将图像的字节插入到数据库中,这有一个简单的修复。 You don't even need to use the Image class;您甚至不需要使用Image class; simply read the bytes of the file and load them into the table:只需读取文件的字节并将它们加载到表中:

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.

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