Download the VARBINARY image

Asked

Viewed 210 times

1

I have images saved in an SQL database on varbinary, I would like to know how to bring it back in my application and download it to the machine in some format (.png, .jpg).

I’m programming with Visual Studio, in the C language#.

Follow code from the button I’m using to upload and save to the bank:

private void button6_Click(object sender, EventArgs e)
    {

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string nomeArquivo = openFileDialog1.FileName;
            Bitmap bmp = new Bitmap(nomeArquivo);
            pictureBox1.Image = bmp;
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, ImageFormat.Bmp);
            byte[] imagem1 = ms.ToArray();

            SqlConnection conn = new SqlConnection(@"Data Source=DESKTOP-7FBA9V8\SQLEXPRESS;Initial Catalog=VALIDACAO;Integrated Security=True");
            SqlCommand comand = new SqlCommand("insert into solicitacao (imagem1) values (@imagem1)", conn);

            SqlParameter paramimagem1 = new SqlParameter("@imagem1", SqlDbType.Binary);
            paramimagem1.Value = imagem1;

            comand.Parameters.Add(paramimagem1);

            conn.Open();
            comand.ExecuteNonQuery();
            conn.Close();


        }

    }
  • Gabriel, have you made any attempt? there is no other code that is relevant to your doubt, because the example that Voce posted was how you recorded the image.

  • And by the way... how will you know if it’s a jpg or png?

1 answer

1

Implement the following method:

private static Image GetImage()
{
    using (SqlConnection conn = new SqlConnection(@"Data Source=DESKTOP-7FBA9V8\SQLEXPRESS;Initial Catalog=VALIDACAO;Integrated Security=True"))
    using (SqlCommand comand = conn.CreateCommand(@"SELECT TOP 1 imagem1 FROM solicitacao", conn))
    {
        conn.Open();

        var arrByte = comand.ExecuteScalar() as byte[];

        using (var ms = new MemoryStream(arrByte))
        {
            return Image.FromStream(ms);
        }
    }
}

Then you just have to invoke it and assign the value returned to PictureBox:

pictureBox1.Image = GetImage();

Information collected from Soen:

Retrieve varbinary(MAX) from SQL Server to byte[] in C#
Byte Array to Image Conversion

Browser other questions tagged

You are not signed in. Login or sign up in order to post.