0

I'm trying to retrieve an image saved in postgresql database in BYTEA format, but I'm having difficulties in transforming the byte array to image using C#. I'm getting "INVALID PARAMETERS" as a return. I've been trying for days and still haven't been able to. Can anyone help me?

    byte[] ObjectToByteArray(object obj)
    {
        if (obj == null)
            return null;
        BinaryFormatter bf = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream())
        {
            bf.Serialize(ms, obj);
            return ms.ToArray();
        }
    }

    public Image byteArrayToImage(byte[] byteArrayIn)
    {
        try
        {
            using (MemoryStream mStream = new MemoryStream(byteArrayIn))
            {
                return Image.FromStream(mStream);
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

    private void dgv_empresa_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        int id = Convert.ToInt32(dgv_empresa.SelectedCells[0].OwningRow.Cells[9].Value);
        if (id != 0)
        {
            try
            {
                string query = " SELECT p.photo_img " +
                        " FROM empresa as e, photo as p " +
                        " WHERE e.empresa_img = " + id + " AND " +
                        " e.empresa_img = p.photo_id; ";

                conexao.Open();
                dgv_empresa.Rows.Clear();
                DataTable dados = new DataTable();
                NpgsqlDataAdapter adaptador = new NpgsqlDataAdapter(query, conexao);
                adaptador.Fill(dados);

                Image imagem = null;

                if (dados.Rows.Count > 0)
                {
                    foreach (DataRow linha in dados.Rows)
                    {
                        byte[] binary = ObjectToByteArray(linha[0]);
                        MemoryStream ms = new MemoryStream(binary, 0, binary.Length);
                        ms.Position = 0;
                        imagem = Image.FromStream(ms, true);
                        Image i = byteArrayToImage(binary);
                    }
                }
                pct_Imagem.Image = imagem;
            }
            catch (Exception ex)
            {
                conexao.Close();
                MessageBox.Show(ex.Message, "Erro no Banco de Dados!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //dgv_empresa.Rows.Clear();
            }
            finally
            {
                conexao.Close();
            }

}

5
  • 1
    If you inserted the Image bytes in a BYTEA Column, then just cast the content to byte[], then you have var Image = (Image)new ImageConverter().ConvertFrom([bytes]); -- Your code is doing weird things: why are using a DataTable to retrieve an Image by ID, clear rows of a DataGridView, then start a loop... Just create a data reader and get the content of the first Column, cast to byte[]. Commented Jun 18, 2022 at 0:04
  • 1
    BinsryFormatter has no reason for being in this code, and won't produce a valid image file, that's for sure. Just save the image's binary data in the database directly, and read the byte[] directly. Commented Jun 18, 2022 at 0:05
  • Here, second result in a quick search: How to insert and retrieve image from PostgreSql using C# (the first, as usual, is ancient) Commented Jun 18, 2022 at 0:08
  • Gentlemen, I could see that the error is in converting the object returned by the database search to byte[], I tested the conversion between byte to image and from image to byte in numerous ways, and it worked, I tested applying it in the PictureBox itself, and also in an Image variable. It worked perfectly, I checked the Length of the byte[] returned, and I realized that the difference between the one returned without the search for the bank is huge. Commented Jun 19, 2022 at 22:02
  • When I convert from object to byte the Length returned greater than I could was 40. When I convert directly from byte to image the length is normal. Varying by image, one image was 647895, another was 57894, and both were successful in converting. Commented Jun 19, 2022 at 22:02

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.