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.
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;
}
Add "PresentationCore " dll from add reference to get System.Windows.Media.Imaging dll referred inorder to get rid of the missing ref error... :)
Related
string address = PictureBox.Location;
give the location of Picturebox image source.
How get address of Picturebox's image source in this order:
C:\\ABC\\XYX\\image.png
The PictureBox load with:
using (MySqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
using (MemoryStream stream = new MemoryStream())
{
if (dr["IMAGE"] != DBNull.Value)
{
byte[] image = (byte[])dr["IMAGE"];
stream.Write(image, 0, image.Length);
Bitmap bitmap = new Bitmap(stream);
pictureBox.Image = bitmap;
}
}
}
}
I did try this one and doesn't help.
string strFileName = PictureBox.ImageLocation + #"\ImageOne.JPG";
Also tried this:
pictureBox.Image.Save("D:\\ImageOne.JPG", ImageFormat.Jpeg);
Gives me this error:
A generic error occurred in GDI+. at System.Drawing.Image.Save
Thanks.
I am having a problem converting a Byte array into an Image type for displaying in an application on Windows Phone 7.
The data is retrieved from a server, and when I upload and download the data it works fine, but I am struggling when converting it back into an Image format.
Can anyone shed some light on this issue for me?
This is my method for turning the Byte array into a BitmapImage,
public BitmapImage decodeImage(byte[] array)
{
MemoryStream ms = new MemoryStream(array, 0, array.Length);
// Convert byte[] to Image
ms.Write(array, 0, array.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(ms);
return bitmapImage;
}
Then this is the code where I try to set the returned BitmapImage to the source for the Image box I am using in the XAML UI.
BitmapImage usrIMG = new BitmapImage();
usrIMG = getJson.decodeImage(userProfile.Photos[0].Image);
profileImage.Source = usrIMG;
I know the code looks mishmashed, and I am declaring things that I dont need to, i have been fiddling with it for ages and I am completely at a loss.
Many Thanks
the following code works fine for me in a quick test for your scenario of using the PhotoChooserTask, and store the selected image in a byte array. You also might want to review your code where you store and retrieve the byte array on your side, to make sure nothing gets lost there.
private byte[] imageBytes;
private void GetPhoto_Click(object sender, RoutedEventArgs e)
{
PhotoChooserTask photoTask = new PhotoChooserTask();
photoTask.Completed += new EventHandler<PhotoResult>(photoTask_Completed);
photoTask.Show();
}
void photoTask_Completed(object sender, PhotoResult e)
{
imageBytes = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(imageBytes, 0, imageBytes.Length);
// save 'imageBytes' byte array to data base ...
}
private void ShowPhoto_Click(object sender, RoutedEventArgs e)
{
// load 'imageBytes' byte array to data base ...
BitmapImage bitmapImage = new BitmapImage();
MemoryStream ms = new MemoryStream(imageBytes);
bitmapImage.SetSource(ms);
myImageElement.Source = bitmapImage;
}
You'll need a WritableBitmap and to know the height and width of the image to be able to do this.
Then you can do something like this:
var result = new WriteableBitmap(width, height);
var ms = new MemoryStream();
ms.Write(myByteArray, myByteArray, myByteArray.Length);
result.SetSource(ms);
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(new MemoryStream(..Binary array Data..));
img1.Source = bitmapImage;
public BitmapImage ByteArraytoBitmap(Byte[] byteArray)
{
MemoryStream stream = new MemoryStream(byteArray);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
return bitmapImage;
}
i used this code before and it's work 100% successfuly.
I am using visual studio 2010, (desktop application) and using LINQ to SQL to save image/video or audio files to database in dataType VarBinary (MAX). This I can do... Problem is, I can't get them and display them in xaml because I can't get the converting part correct. Here is what I have so far (though its not working);
private void bt_Click (object sender, RoutedEventArgs e)
{
databaseDataContext context = new databaseDataContext();
var imageValue = from s in context.Images
where s.imageID == 2
select s.imageFile;
value = imageValue.Single().ToString();
//convert to string and taking down to next method to get converted in image
}
public string value { get; set; }
public object ImageSource //taking from http://stackoverflow.com/
{
get
{
BitmapImage image = new BitmapImage();
try
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.UriSource = new Uri(value, UriKind.Absolute);
image.EndInit();
Grid.Children.Add(image);
}
catch { return DependencyProperty.UnsetValue; } return image;
}
}
I not even sure if I am on the correct track? And I am assuming that video or audio is quite similar methods?
Since your image is stored in binary format in the database, you want to "stream" this into an image object by leveraging the MemoryStream object.
Looking at your code, your solution will look something like this:
BitmapImage bmpImage = new BitmapImage();
MemoryStream msImageStream = new MemoryStream();
msImageStream.Write(value, 0, value.Length);
bmpCardImage.BeginInit();
bmpCardImage.StreamSource = new MemoryStream(msImageStream.ToArray());
bmpCardImage.EndInit();
image.Source = bmpCardImage;
It's very easy, if you have a binary data and want to create an Image object, use this code:
public Image BinaryToImage(byte[] binaryData)
{
MemoryStream ms = new MemoryStream(binaryData);
Image img = Image.FromStream(ms);
return img;
}
If you already have the bytes, to verify that what you saved is correct you can save the bytes to a file and open it....
string tempFile = Path.GetTempFileName();
MemoryStream ms = new MemoryStream(bytes); //bytes that was read from the db
//Here I assume that you're reading a png image, you can put any extension you like is a file name
FileStream stream = new FileStream(tempFile + ".png", FileMode.Create);
ms.WriteTo(stream);
ms.Close();
stream.Close();
//And here we open the file with the default program
Process.Start(tempFile + ".png");
And later you can use the answer of Dillie-O and stream....
Dillie-O's code makes for a very nice extension method:
// from http://stackoverflow.com/questions/5623264/how-to-convert-varbinary-into-image-or-video-when-retrieved-from-database-in-c:
public static BitmapImage ToImage(this Binary b)
{
if (b == null)
return null;
var binary = b.ToArray();
var image = new BitmapImage();
var ms = new MemoryStream();
ms.Write(binary, 0, binary.Length);
image.BeginInit();
image.StreamSource = new MemoryStream(ms.ToArray());
image.EndInit();
return image;
}
I have a table where the picture has been stored and while loading the form i retrieve that data and data is in System.Byte[].
I want this to display in the picture box in window form.
I am using C# language and SQL SERVER 2005
my code goes like this :
Byte[] byteBLOBData = (Byte[])(dt.Rows[count]["stud_photo"]);
MemoryStream ms = new MemoryStream(byteBLOBData);
ms.Write(byteBLOBData, 0, byteBLOBData.Length);
photo.Image = Image.FromStream(ms); --- here i am having an error "Parameter not valid"
Please can anyone help me ...Its very important for my project. Thank you in advance
Set stream position back to the beginning:
ms.Write(byteBLOBData, 0, byteBLOBData.Length);
ms.Position = 0; // THIS !!!!!
photo.Image = Image.FromStream(ms);
The problem is the stream position is at the end so when Image tries to read it, it will read zero byte.
MemoryStream ms = new MemoryStream(byteBLOBData);
Position is indeed your problem. However, the constructor already initializes the memory stream, you don't have to call Write(). Just delete it and the Position will be okay as well.
you need to remove the header of an image and then get the image data and add the code below to return image after only getting image data.
public Image byteArrayToImage(byte[] byteBLOBData )
{
MemoryStream ms = new MemoryStream(byteBLOBData );
Image returnImage = Image.FromStream(ms);
return returnImage;
}
SqlConnection cnn = new SqlConnection(connetionString);
SqlCommand cmd = new SqlCommand(Query, cnn);
MemoryStream stream = new MemoryStream();
cnn.Open();
byte[] image = (byte[])cmd.ExecuteScalar();
stream.Write(image, 0, image.Length);
cnn.Close();
Bitmap bitmap = new Bitmap(stream);
pictureBox1.Image = bitmap;
i am storing images to the database. How to retrieve all the images from the database.
Eg: select images from imagetable
Problem:
Data Logic:
while (dr.Read())
{
///Check for null
if (!dr.IsDBNull(0))
{
try
{
///Converting the image into bitmap
byte[] photo = (byte[])dr[0];
ms = new MemoryStream(photo);
Bitmap bm = new Bitmap(ms);
bmp[i] = bm;
ms.Close();
}
catch (Exception ex)
{
}
}
ASpx.CS page:
Bitmap[] bm= photos.GetImage();
for (int i = 0; i < bm.Length; i++)
{
MemoryStream ms = new MemoryStream();
**bm[i].Save(ms, ImageFormat.Jpeg);**(Error : A generic error occurred in GDI+.)
htmlCode.Append("<li><img ImageUrl=\\\"");
htmlCode.Append(**ms.GetBuffer()**);
htmlCode.Append("\" alt=\"\" width=\"100\" height=\"100\"></li>");
}
Image not getting displayed
Geetha
this is an example from Sql Server
connection.Open();
SqlCommand command1 = new SqlCommand("select imgfile from myimages where imgname=#param", connection);
SqlParameter myparam = command1.Parameters.Add("#param", SqlDbType.NVarChar, 30);
myparam.Value = txtimgname.Text;
byte[] img = (byte[])command1.ExecuteScalar();
MemoryStream str = new MemoryStream();
str.Write(img, 0, img.Length);
Bitmap bit = new Bitmap(str);
connection.Close();
look here
http://www.akadia.com/services/dotnet_read_write_blob.html
For SQL Server 2008 onwards, FILESTREAM is almost certainly the way to go.
Please see: SQL Server 2005 - How do I convert image data type to character format
You need to get the binary data from the DB, and then stream the binary data to the browser as image.
You are setting the Url of the image to be the byte stream - you need to save the image to the hard drive and provide the location.
A much better way would be to set the image url to be a resource handler with parameters that could then retrieve the image from the database and return it as a stream to the browser.