0

I'm trying to insert my bitmap Image into MySQL but the problem is that bitmap is not supported. My error:"System.NotSupportedException: 'Parameter type Bitmap is not supported; see https://fl.vu/mysql-param-type. Value: System.Drawing.Bitmap'". My picture datatype in MySQL is a blob. I wonder if I should change the datatype?

My button Register

private void buttonRegister_Click(object sender, EventArgs e)
{
    String email = textBoxEmail.Text;
    String username = textBoxUsername.Text;
    String password = textBoxPassword.Text;
    String reTypepassword = textBoxReTypePassword.Text;

    UsersClass user = new UsersClass();
    System.Security.Cryptography.AesCryptoServiceProvider keyMaker = new System.Security.Cryptography.AesCryptoServiceProvider();
    keyMaker.KeySize = 128;
    keyMaker.BlockSize = 128;
    keyMaker.GenerateKey();
    byte[] build = keyMaker.Key;
    String Key = Convert.ToBase64String(build);
    //MessageBox.Show(Key);

    string encryptPassword = user.EncryptString(Key, textBoxPassword.Text);


    char[] v = encryptPassword.ToCharArray();
    int c = 0;

    Bitmap bm = new Bitmap(Image);
    for (int w = 0; w < bm.Width; w++)
    {
        for (int h = 0; h < bm.Height; h++)
        {
            if (v.Length > c)
            {
                Color pixel = bm.GetPixel(w, h);
                bm.SetPixel(w, h, Color.FromArgb(pixel.R, pixel.G, Convert.ToInt32(v[c])));
                c++;
            }
        }
    }

    Color p = bm.GetPixel(Image.Width - 1, Image.Height - 1);
    bm.SetPixel(Image.Width - 1, Image.Height - 1, Color.FromArgb(p.R, p.G, Convert.ToInt32(c)));
    Image = (Image)bm;
    imageBox.Image = Image;
 
    

    myconn.openConnection();

    if (password == reTypepassword)
    {
        MySqlCommand cmd = new MySqlCommand("insert into customer values(@id, @username, @email, @password, @Customer_Request,@location,@address,@key, @picture)", myconn.getConnection());
        cmd.Parameters.Add(new MySqlParameter("@id", 0));
        cmd.Parameters.Add(new MySqlParameter("@username", textBoxUsername.Text));
        cmd.Parameters.Add(new MySqlParameter("@email", textBoxEmail.Text));
        cmd.Parameters.Add(new MySqlParameter("@password", encryptPassword));
        cmd.Parameters.Add(new MySqlParameter("@Customer_Request", ""));
        cmd.Parameters.Add(new MySqlParameter("@location", ""));
        cmd.Parameters.Add(new MySqlParameter("@address", textBoxAddress.Text));
        cmd.Parameters.Add(new MySqlParameter("@key", Key));
        cmd.Parameters.Add(new MySqlParameter("@picture", Image));
        cmd.ExecuteNonQuery();
        MessageBox.Show("Success to insert");
    }
    else
    {
        MessageBox.Show("Please enter the correct password");
    }
}
Odain
  • 1
  • 2
  • You should convert Image to a byte[] first. (like https://stackoverflow.com/questions/7350679/convert-a-bitmap-into-a-byte-array) – CyberFox Apr 04 '21 at 12:53
  • The following is written for SQLServer, but can easily be adapted to be used with MySQL (it shows how to save an image to a database and how to read it): https://stackoverflow.com/questions/66612039/why-is-my-image-from-database-not-displaying-properly-in-my-picturebox/66616751#66616751 – Tu deschizi eu inchid Apr 04 '21 at 13:01

1 Answers1

0

This code writes a PNG file (but that could be another type too) to the database, and retrieves it, and stores it to 'test.png'.

using System.IO;
using MySql.Data.MySqlClient;

    class Program
    {
        static void Main(string[] args)
        {
            string filename = @"D:/MySQL Server 8.0/Uploads/d95251abfa0f532b0b332906de4d3181b033b35e76319b807c4948df4fa5aa95.png";

            string Server = "localhost";
            string DatabaseName = "test";
            string UserName = "test";
            string Password = "test";
            string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);

            MySqlConnection conn = new MySqlConnection(connstring);
            conn.Open();

            string sql = "INSERT INTO pic VALUES(@idpic,@caption,@image)";
            var cmd = new MySqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@idpic",null);
            cmd.Parameters.AddWithValue("@caption","test");
            cmd.Parameters.AddWithValue("@image", File.ReadAllBytes(filename));

            var result = cmd.ExecuteNonQuery();
            var lastId = cmd.LastInsertedId;
            Console.WriteLine($"Executing insert resulted in {result}, with idpic={lastId}");

            sql = "SELECT img FROM pic WHERE idpic=@id";
            cmd = new MySqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@id", lastId);
            MySqlDataReader reader = cmd.ExecuteReader();
            reader.Read();
            byte[] picture = (byte[])reader["img"];
            File.WriteAllBytes(@"d:\temp\test.png", picture);
            conn.Close();

        }
    }

The MySQL table was created as follows:

 CREATE TABLE `pic` (
          `idpic` int unsigned NOT NULL AUTO_INCREMENT,
          `caption` varchar(45) NOT NULL,
          `img` longblob NOT NULL,
          PRIMARY KEY(`idpic`)
        ) ENGINE=InnoDB AUTO_INCREMENT = 2 DEFAULT CHARSET = utf8mb4 COLLATE=utf8mb4_0900_ai_ci

There are, at least two settings which needs to be checked.

  1. max_allowed_packet Should be set larger than the maximum file size for the picture.

  2. secure_file_priv If this is set, only files from the directory specified can be inserted to your database.

  3. The user that is connecting to the database should be granted FILE access

Luuk
  • 12,245
  • 5
  • 22
  • 33