Home > Blockchain >  C# SQL to get a picture from the database
C# SQL to get a picture from the database

Time:06-11

I have this code:

private void LoginBTN_Click(object sender, EventArgs e)
{

    var loguser = AutorizeLoginBox.Text;
    var passuser = AutorizePasswordBox.Text;

    SqlDataAdapter adapter = new SqlDataAdapter();
    DataTable table = new DataTable();

    string querrystring = $"select ID, USERLOGIN, USERPASSWORD, USERAVATAR from USERTESTDB where USERLOGIN='{loguser}' and USERPASSWORD='{passuser}'";
    SqlCommand command = new SqlCommand(querrystring, sqldb.getConnection());

    adapter.SelectCommand = command;
    adapter.Fill(table);

    if (table.Rows.Count == 1)
    {
        byte[] arr;
        Image imgcur;
        ImageConverter converter = new ImageConverter();
        arr = (byte[])converter.ConvertFromString(table.Rows[0].ToString(), );
        MemoryStream ms = new MemoryStream(arr);
        Image i = Image.FromStream(ms);
        Program.programpg.avatarbox.Image = i;
    }

    
}

How to upload the image assigned to this user in the database after login. //symbolforfixdetails//symbolforfixdetails//symbolforfixdetails//symbolforfixdetails

This is how the database looks like: enter image description here

Error in this line: arr = (byte[])converter.ConvertFromString(table.Rows[0].ToString() );

Error: System.NotSupportedException: "ImageConverter cannot convert from System.String."

CodePudding user response:

Please Set your Db Column Data type to Varbinary(Max) which you store image's bytes.

Then read this binary to a MemoryStream() as you did but without convert.

If its a winforms project there should be an overload in PictureBox's DataSource (or whatever its name. if i don't remember wrong its name is Image or BackgroundImage) as it accepts directly byte array.

If Winforms, Either you can pass as byte array or Convert to an Image object and set it to datasource.

But if its a web project, then either you could set it as a base64 data/png string or Image object.

Hope this helps.

CodePudding user response:

Try the following code to set the PictureBox.Image from image stored in MSSQL. The code is tested and works as intended.

Part 1: Retrieve image from database and set it to PictureBox.Image:

DataTable table = new DataTable();
byte[] arr=null;
using (SqlConnection cn = new SqlConnection(cs))
{
   cn.Open();
   using (SqlDataAdapter ad = new SqlDataAdapter("select top 1 USERAVATAR from USERTESTDB", cn))//Replace sql qurey with yours
      {
         ad.Fill(table);
      }
 }
 arr = (byte[])table.Rows[0][0];
 //Replace it with [0][3] according to your posted query
 System.Drawing.Bitmap bitmap = null;
 ImageConverter converter = new ImageConverter();
 System.Drawing.Image img = 
 (System.Drawing.Image)converter.ConvertFrom(arr);
 bitmap = (System.Drawing.Bitmap)img;
 pictureBox1.Image = bitmap;

Part 2: Store image in database:

openFileDialog1.ShowDialog();
string path = openFileDialog1.FileName;
byte[] img = null;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
using (SqlConnection cn = new SqlConnection(cs))
{
    cn.Open();
    using (SqlCommand cm = new SqlCommand("insert into USERTESTDB Values (@img)",cn))
        {
            cm.Parameters.Add(new SqlParameter("@img", img));
            cm.ExecuteNonQuery();
         }
  }

You didn't asked about Part2, but I included it to ensure that the image is stored correctly (as binary data) in the database.

You have two problem with your line of code arr = byte[])converter.ConvertFromString(table.Rows[0].ToString());:

  1. You used table.Rows[0] (which returns the entire row) instead of table.Rows[0][x] x=index of image field.
  2. You can't convert String to Image in this way, check Question 3594239 for more details.
  • Related