Reputation: 41128
I have a stored procedure that return a varbinary(max) type data. I want to convert that data into an Image.
But I have problems with this line:
public Image CargarAvatar(string login)
{
System.Object[] Args = new System.Object[1];
Args[0] = login;
DataTable X = new DataTable();
X = TraerDataTable("sp_CargarAvatarUsuario", Args);
byte[] ImagemByte = Convert.to (X.Rows[0][0].ToString());
MemoryStream ms = new MemoryStream();
Image returnImage = Image.FromStream(ms);
return returnImage;
}
Please help! :D
Upvotes: 4
Views: 22179
Reputation: 107
this for convert image to byte array, at it can be inserted into database as it's:
public byte[] imageToByteArray(BitmapImage myimage)
{
MemoryStream ms = new MemoryStream();
WriteableBitmap wb = new WriteableBitmap(myimage);
wb.SaveJpeg(ms, myimage.PixelWidth, myimage.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
return imageBytes;
}
and this for back way:
public static BitmapImage ByteArraytoBitmap(Byte[] byteArray)
{
MemoryStream stream = new MemoryStream(byteArray);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
return bitmapImage;
}
Upvotes: 0
Reputation: 292355
You're trying to create the image from an empty memory stream. Pass the byte array as a parameter to the MemoryStream constructor :
MemoryStream ms = new MemoryStream(ImagemByte);
Upvotes: 0
Reputation: 700152
A varbinary field is returned as a byte array, so you only need to cast it:
byte[] ImagemByte = (byte[])X.Rows[0][0];
Then you use the array to create the memory stream:
MemoryStream ms = new MemoryStream(ImagemByte);
Upvotes: 13
Reputation: 185593
I'm not sure about converting an Int to a byte[] in this case, as I don't see an int anywhere. It's certainly possible to do, I just don't see an application in this case.
You had two real problems. One was creating the byte[], which obviously you know as it wouldn't compile. The second was getting those bytes into the stream.
public Image CargarAvatar(string login)
{
System.Object[] Args = new System.Object[1];
Args[0] = login;
DataTable X = TraerDataTable("sp_CargarAvatarUsuario", Args); // No need to create a new DataTable and overwrite it with the return value of TraerDataTable. One assignment will do.
byte[] ImagemByte = (byte[])X.Rows[0][0]; // If this is an Image in the database, then this is already a byte[] here and just needs to be casted like so.
MemoryStream ms = new MemoryStream(ImagemByte); // You need to pass the existing byte[] into the constructor of the stream so that it goes against the correct data
Image returnImage = Image.FromStream(ms);
return returnImage;
}
Upvotes: 0