Read a BLOB corresponding to an image

0

The following code uses MySqlDataReader to obtain a specific database 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 in a text field easily, as is the case of the "idsocio" field. In the case of the "photoSociety" field, which in the MySQL database is LONGBLOB, how do I load it into the source of an image control?

    
asked by anonymous 23.02.2017 / 11:20

2 answers

1

An example that I found and worked was first you convert the bytes to 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 just assigned to Source of the 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"));

    
23.02.2017 / 15:02
0

Here is a possible answer, the function returns the bitmap image 1 link

edit: you can also convert 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" />
    
23.02.2017 / 12:52