简体   繁体   中英

Converting Byte to Bitmap image

I am getting the byte in database but I cannot convert it to bitmap, I got an exception in Parameter. This is what I've done so far.

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();

I totally stole this answer from 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;
    }
}

try the below. I expect it should work.

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

    // use the Bitmap object `obj` here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM