Read a BLOB corresponding to an image

Asked

Viewed 750 times

0

The following code uses the Mysqldatareader to obtain a database-specific record:

string cmd = string.Format("Select * from socios.socio WHERE idSocio={0}", chave);
MySqlCommand comandoMySQL = new MySqlCommand(cmd, ligacaoBD);
MySqlDataReader reader = comandoMySQL.ExecuteReader();
reader.Read();
MessageBox.Show(reader.GetString("idSocio"));

As you can see, I get the data from a text field easily, as is the case with the "idSocio" field. In the case of the "fotoSocio" field, which in the Mysql database is of the LONGBLOB type, how do I load it to the source of an image control?

2 answers

1


An example I found and worked was first you convert the bytes for a BitmapImage.

public BitmapImage BitmapImageFromBytes(byte[] bytes)
{
    BitmapImage image = null;
    MemoryStream stream = null;
    try
    {
        stream = new MemoryStream(bytes);
        stream.Seek(0, SeekOrigin.Begin);
        System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
        image = new BitmapImage();
        image.BeginInit();
        MemoryStream ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
        ms.Seek(0, SeekOrigin.Begin);
        image.StreamSource = ms;
        image.StreamSource.Seek(0, SeekOrigin.Begin);
        image.EndInit();
    }
    catch (Exception)
    {
        throw;
    }
    finally
    {
        stream.Close();
        stream.Dispose();
    }
    return image;
}

After this conversion is only assigned to the Source of the component Image

MySqlConnection ligacaoBD = new MySqlConnection("server=127.0.0.1;user id=root;Pwd=123123;database=socios;persistsecurityinfo=True");
ligacaoBD.Open();
string cmd = string.Format("Select * from socios.socio WHERE idSocio={0}", 1);
MySqlCommand comandoMySQL = new MySqlCommand(cmd, ligacaoBD);
MySqlDataReader reader = comandoMySQL.ExecuteReader();
reader.Read();

byte[] foto = (byte[])reader["foto"];
image.Stretch = Stretch.Fill;
image.Source = BitmapImageFromBytes(foto);

MessageBox.Show(reader.GetString("idSocio"));

inserir a descrição da imagem aqui

0

Here you have a possible answer, the function returns the image in bitmap 1 https://stackoverflow.com/questions/8257941/retrieve-longblob-from-mysql-in-c-sharp

Edit: you can also convert to an array of bytes and serialize

 Model.ByteArray = (byte[])reader.GetString("fotoSocio")

and in the view..

 @{
var base64 = Convert.ToBase64String(Model.ByteArray);
var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
 }

 <img src="@imgSrc" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.