将字节转换为位图图像

时间:2015-11-08 17:14:28

标签: c# database bitmap byte

我在数据库中获取字节,但我无法将其转换为位图,我在参数中遇到了异常。这是我到目前为止所做的。

con.ConnectionString = MyConnectionString;
con.Open();
OdbcCommand cmds = new OdbcCommand("Select ID from try where kalabaw = 5", con);
OdbcDataAdapter da = new OdbcDataAdapter(cmds);
byte[] image = (byte[])cmds.ExecuteScalar();
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bitmap = (Bitmap)tc.ConvertFrom(image);
pictureBox2.Image = bitmap;
con.Close();

2 个答案:

答案 0 :(得分:0)

我完全从convert array of bytes to bitmapimage

那里偷了这个答案
public BitmapImage ToImage(byte[] array)
{
    using (var ms = new System.IO.MemoryStream(array))
    {
        var image = new BitmapImage();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad; // here
        image.StreamSource = ms;
        image.EndInit();
        return image;
    }
}

答案 1 :(得分:0)

尝试以下方法。我希望它能起作用。

byte[] bytes = GetBytesArrayFromDatabase();
using (MemoryStream ms = new MemoryStream(bytes))
{
    ms.Position = 0;
    Bitmap obj = new Bitmap(ms);

    // use the Bitmap object `obj` here
}
相关问题