如何从 MySQL 中检索 img 到 pictureBox

how to retrieve img from MySQL into pictureBox

我想从 MySQL 中的 Blob 获取图像,然后在 PictureBox 中显示图像。我传入的图像不正确,我不明白如何检索字节数组,因为我当前的数组不正确。

我的代码:

将 img 添加到数据库:

using(OpenFileDialog ofd = new OpenFileDialog())
{
     if (ofd.ShowDialog() == DialogResult.OK)
     {
         byte[] bytes = File.ReadAllBytes(ofd.FileName);
         imageUrl = ofd.FileName.ToString();
         //roundPictureBox1.Image = Image.FromFile(ofd.FileName);
         roundPictureBox2.ImageLocation = imageUrl;
         MySqlConnection con = new MySqlConnection(connectionString);
         con.Open();
         MySqlCommand cmd = new MySqlCommand("INSERT INTO reg.img_table(image, id) VALUES (@image, @id)", con);
         long id = cmd.LastInsertedId;
         Properties.Settings.Default.idImg = id;
         cmd.Parameters.AddWithValue("@image", bytes);
         cmd.Parameters.AddWithValue("@id", id);
         cmd.ExecuteNonQuery();
         con.Close();
     }
}

return 图片:

private Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

主要代码:

private void photoLoad()
{
    string connectionString = "datasource=localhost;" +
                     "port=3306;" +
                     "database=reg;" +
                     "username=root;" +
                     "password=Admin123";

    MySqlConnection con = new MySqlConnection(connectionString);

    byte[] ImageByte = new byte[0];
    string query1 = "select image from reg.img_table where id= @id";
    MySqlCommand cmd = new MySqlCommand(query1, con);
    cmd.Parameters.AddWithValue("@id", Properties.Settings.Default.idImg);
    
    try
    {
         con.Open();
         MySqlDataReader row;
         row = cmd.ExecuteReader();

         while (row.Read())
         {
             ImageByte = (Byte[])(row["image"]); 
         }

         if (ImageByte != null)
         {
             // You need to convert it in bitmap to display the image
             roundPictureBox1.Image = byteArrayToImage(ImageByte);
             roundPictureBox1.Refresh();
         }
    }
    catch (Exception ex)
    {
         MessageBox.Show("Error Img");
    }
}

没有显示错误。登录表单显示,但 PictureBox 不显示照片。

根据您的 OP,您将图像存储在 MySql 数据库的数据库 BLOB 列中。下面显示了如何将图像插入 MySql 数据库 table。然后检索该图像并将其显示在 PictureBox 中。

Download/install NuGet 包: MySql.Data

数据库Table:学生

我选择在 App.config 中存储数据库的连接字符串。

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="MySqlConnectionString" connectionString="Server=localhost;Port=3306;Database=University123;Uid=testAdmin;Pwd=password123;" />
    </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
    </startup>
</configuration>

创建一个class:(名称:HelperMySql.cs)

  • 在 VS 菜单中,单击 项目
  • Select 添加Class...

添加以下using语句:

  • 使用 System.Configuration;
  • 使用 System.IO;
  • 使用 MySql.Data.MySqlClient;

HelperMySql.cs

注意:我选择使用 LongBlob 而不是 Blob - 如果需要,可以更改。

public class HelperMySql
{
    private string _connectionStr = ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ConnectionString;
    //private string _connectionStr = "Server=localhost;Port=3306;Database=University123;Uid=testAdmin;Pwd=password123;";

    public void ExecuteNonQuery(string sqlText)
    {
        using (MySqlConnection con = new MySqlConnection(_connectionStr))
        {
            //open
            con.Open();

            using (MySqlCommand cmd = new MySqlCommand(sqlText, con))
            {
                //execute
                cmd.ExecuteNonQuery();
            }
        }
    }

    public byte[] GetImageAsByteArray(string filename)
    {
        //reads image from file and returns as byte[]

        if (String.IsNullOrEmpty(filename))
            throw new Exception("Error (GetImageAsByteArray) - Filename not specified.");
        else if(!File.Exists(filename))
            throw new Exception($"Error (GetImageAsByteArray) - File '{filename}' doesn't exist.");
        
        return System.IO.File.ReadAllBytes(filename);
    }


    public void TblStudentCreate()
    {
        //for mySQL, use backticks (ex: `First Name`) if tablename has space in it
        string sqlText = @"CREATE TABLE Student (Id int NOT NULL AUTO_INCREMENT,
                                                       FirstName varchar(50),
                                                       LastName  varchar(75),
                                                       Img longblob,
                                                       CONSTRAINT PK_Student_ID PRIMARY KEY(ID));";

        ExecuteNonQuery(sqlText);

        Debug.WriteLine("Info: Table created (Student)");
    }

    public void TblStudentInsert(string firstName, string lastName, string filename)
    {
        if (String.IsNullOrEmpty(filename))
            throw new Exception("Error (TblStudentInsert) - Filename not specified.");
        else if (!File.Exists(filename))
            throw new Exception($"Error (TblStudentInsert) - File '{filename}' doesn't exist.");

        byte[] imageBytes = File.ReadAllBytes(filename);

        TblStudentInsert(firstName, lastName, imageBytes);
    }

    public void TblStudentInsert(string firstName, string lastName, byte[] imageBytes)
    {
        string sqlText = "INSERT INTO Student (FirstName, LastName, Img) VALUES (@firstName, @lastName, @imageBytes);";

        using (MySqlConnection con = new MySqlConnection(_connectionStr))
        {
            //open
            con.Open();

            using (MySqlCommand cmd = new MySqlCommand(sqlText, con))
            {
                //add parameters

                //FirstName
                if (!String.IsNullOrEmpty(firstName))
                    cmd.Parameters.Add("@firstName", MySqlDbType.VarChar).Value = firstName;
                else
                    cmd.Parameters.Add("@firstName", MySqlDbType.VarChar).Value = DBNull.Value;

                //LastName
                if (!String.IsNullOrEmpty(lastName))
                    cmd.Parameters.Add("@lastName", MySqlDbType.VarChar).Value = lastName;
                else
                    cmd.Parameters.Add("@lastName", MySqlDbType.VarChar).Value = DBNull.Value;
                
                //Img
                if (imageBytes != null)
                    cmd.Parameters.Add("@imageBytes", MySqlDbType.LongBlob).Value = imageBytes;
                else
                    cmd.Parameters.Add("@imageBytes", MySqlDbType.VarChar).Value = DBNull.Value;

                //execute
                cmd.ExecuteNonQuery();
            }
        }
    }

    public byte[] GetStudentImage(int id)
    {
        string sqlText = "SELECT img from Student where Id = @id;";

        using (MySqlConnection con = new MySqlConnection(_connectionStr))
        {
            //open
            con.Open();

            using (MySqlCommand cmd = new MySqlCommand(sqlText, con))
            {
                cmd.Parameters.Add("@id", MySqlDbType.Int32).Value = id;
                
                //execute
                using (MySqlDataReader dr = cmd.ExecuteReader())
                {
                    if (dr.HasRows)
                    {
                        while(dr.Read())
                        {
                            //get image from database and return as byte[]
                            if (dr["Img"] != null && dr["Img"] != DBNull.Value)
                                return (byte[])dr["Img"];
                        }
                    }
                }
            }
        }

        return null;
    }
}

用法:将记录插入数据库

private HelperMySql helper = new HelperMySql();
                 ...
helper.TblStudentInsert("John", "Smith", @"D:\Images\Students\JohnSmith.png");

用法:在PictureBox中显示图片(名称:pictureBox1)

int studentId = 1;
byte[] imageBytes = helper.GetStudentImage(studentId);

using (MemoryStream ms = new MemoryStream(imageBytes))
{
    pictureBox1.Image = Image.FromStream(ms);
    pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; //fit to size
    pictureBox1.Refresh();
}
   

注意:您可以考虑将文件名存储在数据库中,而将实际文件存储在文件系统中。

资源: