'Converting binary data to image in C#
I was stuck with how to retrieve an image from MySQL database and convert it from Binary format to Bitmap Image to display it in ASP:Image or HTML Image. I am able to upload image but its being converted to Binary data and I couldn't understand how to convert it back to Bitmap format :(
protected void Button2_Click(object sender, EventArgs e)
{
cmd = new OdbcCommand("SELECT picture from profile limit 1", MyConnection);
MyConnection.Open();
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
Response.Write("No rows");
}
if(dr.Read())
{
// WHAT TO CODE HERE?
}
}
Anybody please help me in fill the code with WHAT TO CODE HERE part.
Solution 1:[1]
If you modify this method, it should do the trick:
public BitmapImage ConvertToImage(System.Data.Linq.Binary binary)
{
byte[] buffer = binary.ToArray();
MemoryStream stream = new MemoryStream(buffer);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
return image;
}
Solution 2:[2]
Add "PresentationCore " dll from add reference to get System.Windows.Media.Imaging dll referred inorder to get rid of the missing ref error... :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MBX |
| Solution 2 | Vidhya Sagar |
