Doubts about converting from Byte to Image in c# You are showing a strange and unusual error

Asked

Viewed 1,078 times

0

I am trying to convert the bytes that are in a database to Image in a Picturebox in C# 2012, but when it arrives on a given line it says that the parameter is invalid, an abnormal error that never happened before, I did a Debug and the only thing I could notice is that the parameter Staff.Photo which brings the database bytes has only 13 byte and the error occurs in the method that converts from byte for image.

I would appreciate it if the forum developers could post this error, I have given everything I have and achieved success, I thank you already.

Below I have the Methods:

1st Method: Allowing to display database data in form objects through the BLL Code class:

public Image ByteToImage(byte[] imageArray)
    {
        ImageConverter converter = new ImageConverter();
        return (Image)converter.ConvertFrom(imageArray);
    }

        private void mCarregarCampos()
        {
            clsFuncionarioDTO Funcionario = new clsFuncionarioDTO();
            if (this.Text == "FUNCIONÁRIOS")
            {
                if (cbxCodFuncionario.Text != "")
                {  
                    bll.CarregarFuncionario(Funcionario, int.Parse(cbxCodFuncionario.Text));
                }
            }
            txtFuncionario.Text = Funcionario.Funcionario;
            txtEmail.Text = Funcionario.Email;
            txtSkype.Text = Funcionario.Skepe;
            ptbFoto.Image = null;
            if (Funcionario.Foto != null && Funcionario.Foto.Length > 0)
            {
                ptbFoto.Image = ByteToImage(Funcionario.Foto)
            }
   }

2nd Method: which is in the class BLL that contains the SQL Code intro:  

 public void CarregarFuncionario(clsFuncionarioDTO Funcionario,int comboBox)
        {
            string comando = "SELECT Funcionario,Email,Skype,Foto FROM tblFuncionarios WHERE  tblFuncionarios.CodFuncionario = " + comboBox + " ";
            string campo = "Funcionario"; 
            string campo1 = "Email";
            string campo2 = "Skype";
            string campo3 = "Foto";
            SqlDataReader seleccione = mMostrarDados(comando);
            while (seleccione.Read())
            {
                Funcionario.Funcionario = seleccione[campo].ToString();
                Funcionario.Email = seleccione[campo1].ToString();
                Funcionario.Skepe = seleccione[campo2]ToString(); 
                if (seleccione[campo3] != System.DBNull.Value)
                    Funcionario.Foto = (byte[])seleccione[campo3];
            }  
            seleccione.Close();  
       }

3rd Method: Communicates directly with the Code database:

class clsABD
    {
        public SqlConnection conexao;
        private SqlCommand comando;
        private SqlCommandBuilder comandoB;
        private SqlDataAdapter seleccione;
        private SqlDataReader seleccione1;
        private DataTable tabela; 
        private string caminho = String.Format("Data Source=Dario;Initial Catalog=DB_EMPRESA;Integrated Security=True");
        public void LigarBD()
        {
            if (conexao != null)
                conexao.Close();
            try
            {
                conexao = new SqlConnection(caminho);
                conexao.Open();
            }
            catch (Exception ex)
            { 
                throw new Exception ("Erro! Aplicação não conseguio ligar a Base de Dados!"+ex.Message);
            }  
        }
        public void DesligarBD()
        {
            try
            {
                conexao = new SqlConnection(caminho);
                conexao.Close();
            }
            catch (Exception ex)
            {      
                throw new Exception ("Erro ao tentar desligar a Base de Dados!"+ex.Message);
            }    
        }
        public void mExecutarComandos(string comandoSQL)
        {
            LigarBD();
            comando = new SqlCommand(comandoSQL,conexao);
            try
            {
                comando.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao executar camandoSQL!" + ex.Message);
            }
            finally
            {
                DesligarBD();  
           }
        }
        public DataTable mCriarTabela(string comandoSQL)
        {
            LigarBD();
            tabela = new DataTable();
            seleccione = new SqlDataAdapter(comandoSQL,conexao);
            comandoB = new SqlCommandBuilder(seleccione);
            seleccione.Fill(tabela);
            DesligarBD();  
            return tabela; 
        }
        public SqlDataReader mCriarTabelaLeitura(string comandoSQL)
        {
            LigarBD();
            comando = new SqlCommand(comandoSQL, conexao);
            seleccione1  = comando.ExecuteReader();
            //DesligarBD(); 
            return seleccione1;  
        }
    }

This is all in accordance, load all fields except the Photo field on Picturebox, but at the time of executing displays the following error:

Invalid parameter exactly in the method that converts the byte to image.

Observing: I’m programming in 3 layers

  • 2

    Obs.: Don’t use the tag visual-studio for problems that are not related to the IDE. See that question if you have any questions.

  • 1

    related: http://answall.com/questions/94219/image-para-byte

2 answers

5

You don’t need all this to convert an array of byte for an object Image.

You can do it this way:

public Image byteArrayToImage(byte[] img) 
{
    using (var ms = new MemoryStream(img))
    {
        return Image.FromStream(ms);
    }
}

It’s important not to forget using because he makes the call from Dispose() at the end of the operation. If the Dispose is not called, resources will not be released and the image will be unavailable for other operations.

  • Good evening I tried using the various ways presented but still there was no success. But I will post the full code:

1

Code of array of bytes (byte[]) for Image:

public Image ByteToImage(byte[] image)
{
     MemoryStream ms = new MemoryStream(image);
     return Image.FromStream(ms);
}

and this code with the class Imageconverter

public Image ByteToImage(byte[] image)
{
    ImageConverter converter = new ImageConverter();
    return (Image)converter.ConvertFrom(image);
}

Has a complete and ready code.

References:

Browser other questions tagged

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