[英]How can I read a byte[] out of the database and convert it to an image?
我有一个存储过程,返回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
varbinary字段作为字节数组返回,因此您只需要将其强制转换:
byte[] ImagemByte = (byte[])X.Rows[0][0];
然后使用该数组创建内存流:
MemoryStream ms = new MemoryStream(ImagemByte);
在这种情况下,我不确定将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;
}
您正在尝试从空的内存流创建图像。 将字节数组作为参数传递给MemoryStream构造函数:
MemoryStream ms = new MemoryStream(ImagemByte);
这用于将图像转换为字节数组,它可以插入到数据库中,因为它是:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.