Doubts about converting from Byte into Image in C # You are experiencing a strange and unusual error [duplicate]

0

I'm trying to convert the bytes that are in a database into a PictureBox in C # 2012, but when it arrives on a particular line it says that the parameter is invalid, an abnormal error that never happened before , I made a Debug and the only thing I could notice is that the Funcionario.Photo parameter that brings the bytes of the database has only and the error occurs in method that converts from byte to image.

I would appreciate if the programmers of the forum could post on this error, I have given everything I have and I have obtained successes, thank you in the end.

Below I have the Methods:

1st Method: This allows you to display the data of the database in the objects of the form through the class BLL Code:

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 BLL class that contains the SQL statement Code:       

 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: That communicates directly with the database Code:

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 in compliance, it loads all fields except the Picture field in the PictureBox , but at the time of execution it displays the following error:

  

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

Note: I'm programming in 3 layers

    
asked by anonymous 09.01.2017 / 00:28

2 answers

5

You do not need all this to convert an array of byte to a Image object.

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 it calls Dispose() at the end of the operation. If Dispose is not called, the features will not be freed and the image will be unavailable for other operations.

    
09.01.2017 / 00:38
1

Code from array from bytes ( byte[] ) to 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);
}

You have a complete code and ready .

References:

09.01.2017 / 00:38