简体   繁体   中英

How to convert data type longtext with base64 to image from data base to gridview on specific column?

i call a database to get data in column with data type longtext that contain string that i've encoded from image with base64

 string insertQuery = "SELECT product_id, picture FROM product WHERE aksi != 'Deleted' ";
 etc...
 dataGridView1.DataSource = dtblProduct;

the column with data type longtext is picture

i want to convert the longtext 's data in column picture with base64 and display it on gridview along with product id

i've tried, but the error says 'The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. '

string showpic = dataGridView1.Columns[1].ToString();
byte[] imageBytes = Convert.FromBase64String(showpic);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
Image myimage = Image.FromStream(ms, true);

DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
imageColumn.Image = myimage;

According to your description, you want to display a picture in a column of datagridview.

I suggest that when designing the form, add two columns in the datagridview, namely product_id, picture.

The data type of the picture column is DataGridViewImageColumn.

You can try the following code to solve this problem.

public void Table()
        {

            dataGridView1.Rows.Clear();
            MySqlConnection conn = new MySqlConnection("…");           
            conn.Open();
            MySqlCommand cmd = new MySqlCommand("select product_id,picture from product WHERE aksi != 'Deleted'", conn);
            MySqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                string id, base64;
                id = reader["product_id"].ToString();
                base64 = reader["picture"].ToString();
                byte[] bytes = Convert.FromBase64String(base64);
                MemoryStream memStream = new MemoryStream(bytes);
                BinaryFormatter binFormatter = new BinaryFormatter();
                Image img = (Image)binFormatter.Deserialize(memStream);                            
                dataGridView1.Rows.Add(new object[] { id,img});
            }
            reader.Close();
        }
private void Form1_Load(object sender, EventArgs e)
        {
            Table();
      }

Result: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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