如何在byte[]中转换对象



CONVERT OBJECT TO BYTE[]

你好吗?我在转换对象(通过查询返回到Postgres数据库)到byte[]方面遇到困难,我以几种不同的方式进行测试,但我无法获得存储在数据库中引用图像的数组的总大小。我在数据库中保存了一张图像,并且在我尝试检索它的每种方式中,字节[]都有不同的大小,这取决于我如何从对象转换到字节[]。我得到的最大数组大小是length = 42,图像的长度是675486。我试过这些方法。

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

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

结果是length = 42

最后两个给我带来了最好的结果。但它仍然不是一个有效的字节数组。有人能帮帮我吗?

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

您可以使用我将类序列化为JSON文本然后将其转换为byte[]的方法。您可以将其序列化为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();        }

相关内容

  • 没有找到相关文章

最新更新