0

CONVERT OBJECT TO BYTE[]

Hello how are you? I'm having difficulties in converting an object (returned by a query to the Postgres database) to byte[], I test in several different ways but I can't get the total size of the array stored in the database referring to the image. I have a single image saved in the database, and in each way I try to retrieve it, the byte[] comes with a different size depending on how I do the conversion from object to byte[]. The biggest array size I got was length = 42, the image has length = 675486. I've tried these ways.

 using (conexao)
        {
            string sQL = " SELECT p.photo_img " +
                        " FROM empresa as e, photo as p " +
                        " WHERE e.empresa_img = " + id + " AND " +
                        " e.empresa_img = p.photo_id; ";

            using (var command = new NpgsqlCommand(sQL, conexao))
            {
                byte[] productImageByte = null;
                conexao.Open();
                var rdr = command.ExecuteReader();

                while (rdr.Read())
                {
                    productImageByte = (byte[])rdr[0];
                }
                rdr.Close();
                if (productImageByte != null)
                {
                    using (MemoryStream productImageStream = new MemoryStream(productImageByte))
                    {
                        ImageConverter imageConverter = new System.Drawing.ImageConverter();
                        pct_Imagem.Image = imageConverter.ConvertFrom(productImageByte) as System.Drawing.Image;
                    }
                }
            }

        }

The result of this was length = 13

    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();
                DataTable dados = new DataTable();
                NpgsqlDataAdapter adaptador = new NpgsqlDataAdapter(query, conexao);
                adaptador.Fill(dados);

                if (dados.Rows.Count > 0)
                {
                    foreach (DataRow linha in dados.Rows)
                    { 
                        byte[] data = ObjectToByteArray(linha[0]);

                        var imagem = (Image)new ImageConverter().ConvertFrom(data);
                        pct_Imagem.Image = imagem;
                    }
                }

            }
            catch (Exception ex)
            {
                conexao.Close();
                MessageBox.Show(ex.Message, "Erro no Banco de Dados!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                conexao.Close();
            }
         }
    }

    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();
        }
     }

The result of this was length = 42

These last two brought me the best results. But still, it's not a valid byte array. Can someone help me?

8
  • Do not use string concatenation to create an SQL command. Use parameterized statements. See why it's a bad idea and how to fix it. Commented Jun 19, 2022 at 23:15
  • Hello, thank you very much for the tip, I will police myself not to make this mistake again... Thank you very much!!! @gunr2171 Commented Jun 19, 2022 at 23:20
  • You have already asked this question. First of all, you need to show how you're saving this image to your database. Then, don't use a DataTable and a DataAadapter to retrieve the image, just execute a DataReader, get its first Column (since you're getting just one), cast the Column's Value to byte[] -- This assumes the Image has been saved - correctly - as a byte array. It also assumes that your query is correct. -- Maybe post the Table definition. Commented Jun 20, 2022 at 0:37
  • Maybe this can help you: stackoverflow.com/questions/5932193/… Commented Jun 20, 2022 at 0:38
  • As already mentioned, use this post How to insert and retrieve image from PostgreSql using C# as guide. -- Not very useful to thank people for their suggestions when you don't follow them in any way. Commented Jun 20, 2022 at 0:39

2 Answers 2

0

I managed to do, what I needed to adjust to not use Connetion, but create and discard in each block that was to be used

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

you can use this method that I serialized the class into JSON text and then converted it to byte[]. You can either serialize it to XML

private async Task<byte[]> CreateByteArrayAsync(object obj)
        {
            using var memoryStream = new MemoryStream();
            await using var writer = new StreamWriter(memoryStream);
            var jsonText = JsonConvert.SerializeObject(obj);
            await writer.WriteAsync(jsonText);
            await writer.FlushAsync();

            return memoryStream.ToArray();        }

3 Comments

Hello, I tested the way you indicated, and the result was a little strange, it only returned 1 byte
@alysonpereira Can you provide more information? I just tested the code, And it's working. I suggest tracing the code and debugging thejsonText. To be sure, you can use JsonConvert from Newtonsoft.Json NuGet
@alysonpereira it was using async methods but not awaiting them. Proposing update.

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.