How can I read byte [] from the database and convert it to an image?

I have a stored procedure that returns data of type varbinary (max). I want to convert this data to 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

+4
source share
4 answers

The varbinary field is returned as a byte array, so you only need to drop it:

 byte[] ImagemByte = (byte[])X.Rows[0][0]; 

Then you use an array to create a memory stream:

 MemoryStream ms = new MemoryStream(ImagemByte); 
+10
source

I am not sure about converting Int to byte [] in this case, as I do not see anywhere. Of course, this is possible, I just do not see the application in this case.

You had two real problems. One of them created a byte [], which, obviously, you know, since it will not compile. The second way was to get these 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; } 
0
source

You are trying to create an image from an empty memory stream. Pass the byte array as a parameter to the MemoryStream constructor:

 MemoryStream ms = new MemoryStream(ImagemByte); 
0
source

this is to convert the image to a byte array, while it can be inserted into the database like this:

 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 is for the return trip:

 public static BitmapImage ByteArraytoBitmap(Byte[] byteArray) { MemoryStream stream = new MemoryStream(byteArray); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(stream); return bitmapImage; } 
0
source

All Articles