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();
}
}
byte[], then you havevar 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 tobyte[].BinsryFormatterhas 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 thebyte[]directly.