简体   繁体   中英

How to convert object in byte[] c#

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?

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 byte[] CreateByteArray(object obj)
        {
            using var memoryStream = new MemoryStream();
            using var writer = new StreamWriter(memoryStream);
            var jsonText = JsonConvert.SerializeObject(obj);
            writer.WriteAsync(jsonText);
            writer.Flush();

            return memoryStream.ToArray();
        }

我设法做到了,我需要调整以不使用连接,而是在每个要使用的块中创建和丢弃

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM