1

I have a problem with the code c# below, i should save a binary image in a sql server database 2014, i did the function to convert the image to binary, the image select it with a button, The problem is that when I save the database to 0x00 in the field Immagine, how can I fix this type of error? the Immagine field format is binary

QUERY:

private void buttonCaricaImmagine_Click(object sender, EventArgs e)
{            
    OpenFileDialog of = new OpenFileDialog();
    //For any other formats

     of.Filter = "Image Files (*.bmp;*.jpg;*.jpeg,*.png)|*.BMP;*.JPG;*.JPEG;*.PNG";
    if (of.ShowDialog() == DialogResult.OK)
    {

        pictureBoxRapportino.ImageLocation = of.FileName;
        imm = pictureBoxRapportino.Image;
        checkImage = 1;
    }
}

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    ImageConverter _imageConverter = new ImageConverter();
    byte[] xByte = (byte[])_imageConverter.ConvertTo(imageIn, typeof(byte[]));
    return xByte;
}

private void buttonInserimento_Click(object sender, EventArgs e)
{
    try
    {
        if(checkImage==1 && textBoxNumeroDocumento.Text != "")
        {
            //controlla dati
            int NumeroDocumento = int.Parse(textBoxNumeroDocumento.Text);

             byte[] ImmagineBinaria = ImageToByteArray(imm);
             string BinaryImageCast = Encoding.UTF8.GetString(ImmagineBinaria);
             //MessageBox.Show("Immagine in formato binario: " + BinaryImageCast);

            //inserisco i dati nel database
            SqlConnection conn = db.apriconnessione();

            String query = "Insert into Rapporto(IdCantiere,IdUtenteCreazione,NumeroDocumento,Data,Immagine) values(@IdCantiere,@IdUtenteCreazione,@NumeroDocumento,@Data,@Immagine) ";

            using (SqlCommand command = new SqlCommand(query, conn))
            {                       
                command.Parameters.Add("@IdCantiere", SqlDbType.Int).Value = IdCantiere;
                command.Parameters.Add("@IdUtenteCreazione", SqlDbType.Int).Value = u.IdUtente;
                command.Parameters.Add("@NumeroDocumento", SqlDbType.Int).Value = int.Parse(textBoxNumeroDocumento.Text);
                command.Parameters.Add("@Data", SqlDbType.DateTime).Value = dateTimePickerData.Value;
                command.Parameters.Add("@Immagine", SqlDbType.Binary).Value = ImmagineBinaria;
                command.ExecuteNonQuery();

            }

            db.chiudiconnessione();
            conn.Close();

        }

        else
        {
            MessageBox.Show("Devi compilare tutti i campi");
        }



    }

    catch(Exception ex)
    {
        MessageBox.Show("Errore: controlla i formati "+ex);
    }

}

Database Sql Server: enter image description here

Table Schema

CREATE TABLE Rapporto(
    IdRapporto int IDENTITY(1,1) PRIMARY KEY,
    IdCantiere int FOREIGN KEY REFERENCES Cantiere(IdCantiere),
    IdUtenteCreazione int FOREIGN KEY REFERENCES Utente(IdUtente),
    NumeroDocumento varchar(5000) default NULL,
    Data datetime default NULL,
    Immagine varbinary(MAX) default NULL,

); 
8
  • akadia.com/services/dotnet_read_write_blob.html Commented Sep 12, 2017 at 7:58
  • I guess "SqlTDbype.Binary" is not actually what you think it is. Commented Sep 12, 2017 at 8:03
  • how could it be binary? it would have to be the varbinary(max) or (obsolete) an image data type. Commented Sep 12, 2017 at 8:03
  • 1
    "Array of type Byte. A fixed-length stream of binary data ranging between 1 and 8,000 bytes." Commented Sep 12, 2017 at 8:06
  • @dlatikay I tried to change the format in varbinary (MAX) but I always have the same result Commented Sep 12, 2017 at 8:06

1 Answer 1

3

Try this use conv_photo() this will help you.

  private void buttonCaricaImmagine_Click(object sender, EventArgs e)
            {
                OpenFileDialog of = new OpenFileDialog();
                //For any other formats

                of.Filter = "Image Files (*.bmp;*.jpg;*.jpeg,*.png)|*.BMP;*.JPG;*.JPEG;*.PNG";
                if (of.ShowDialog() == DialogResult.OK)
                {

                    pictureBoxRapportino.ImageLocation = of.FileName;
                    imm = pictureBoxRapportino.Image;
                    checkImage = 1;
                }
            }
            //this will convert your picture and save in database
            void conv_photo()
            {
                MemoryStream ms;
                if (pictureBoxRapportino.Image != null)
                {
                    ms = new MemoryStream();
                    pictureBoxRapportino.Image.Save(ms, ImageFormat.Jpeg);
                    byte[] photo_aray = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(photo_aray, 0, photo_aray.Length);
                    command.Parameters.Add("@Immagine", SqlDbType.Binary).Value = photo_aray;
                }
            }



            private void buttonInserimento_Click(object sender, EventArgs e)
            {
                try
                {
                    if (checkImage == 1 && textBoxNumeroDocumento.Text != "")
                    {
                        //controlla dati
                        int NumeroDocumento = int.Parse(textBoxNumeroDocumento.Text);

                        //inserisco i dati nel database
                        SqlConnection conn = db.apriconnessione();

                        String query = "Insert into Rapporto(IdCantiere,IdUtenteCreazione,NumeroDocumento,Data,Immagine) values(@IdCantiere,@IdUtenteCreazione,@NumeroDocumento,@Data,@Immagine) ";

                        using (SqlCommand command = new SqlCommand(query, conn))
                        {
                            command.Parameters.Add("@IdCantiere", SqlDbType.Int).Value = IdCantiere;
                            command.Parameters.Add("@IdUtenteCreazione", SqlDbType.Int).Value = u.IdUtente;
                            command.Parameters.Add("@NumeroDocumento", SqlDbType.Int).Value = int.Parse(textBoxNumeroDocumento.Text);
                            command.Parameters.Add("@Data", SqlDbType.DateTime).Value = dateTimePickerData.Value;
                            conv_photo();
                            command.ExecuteNonQuery();

                        }

                        db.chiudiconnessione();
                        conn.Close();

                    }

                    else
                    {
                        MessageBox.Show("Devi compilare tutti i campi");
                    }

                }

                catch (Exception ex)
                {
                    MessageBox.Show("Errore: controlla i formati " + ex);
                }

            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.