我有一个返回varbinary(max)类型数据的存储过程。我想将该数据转换为图像。
但我对这一行有疑问:
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;
}
请帮忙! :d
答案 0 :(得分:11)
varbinary字段作为字节数组返回,因此您只需要转换它:
byte[] ImagemByte = (byte[])X.Rows[0][0];
然后使用该数组创建内存流:
MemoryStream ms = new MemoryStream(ImagemByte);
答案 1 :(得分:0)
在这种情况下,我不确定将Int转换为byte [],因为我在任何地方都看不到int。这当然是可能的,我只是在这种情况下看不到应用程序。
你有两个真正的问题。一个是创建byte [],显然你知道它不会编译。第二个是将这些字节放入流中。
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;
}
答案 2 :(得分:0)
您正尝试从空的内存流创建图像。将字节数组作为参数传递给MemoryStream构造函数:
MemoryStream ms = new MemoryStream(ImagemByte);
答案 3 :(得分:0)
这用于将图像转换为字节数组,因为它可以插入到数据库中:
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;
}
这是回来的方式:
public static BitmapImage ByteArraytoBitmap(Byte[] byteArray)
{
MemoryStream stream = new MemoryStream(byteArray);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
return bitmapImage;
}