How can I convert byte[] to BitmapImage?

后端 未结 4 846
死守一世寂寞
死守一世寂寞 2021-01-17 12:03

I have a byte[] that represents the raw data of an image. I would like to convert it to a BitmapImage.

I tried several examples I found but

4条回答
  •  庸人自扰
    2021-01-17 12:23

    I ran across this same error, but it was because my array was not getting filled with the actual data. I had an array of bytes that was equal to the length it was supposed to be, but the values were all still 0 - they had not been written to!

    My particular issue - and I suspect for others that arrive at this question, as well - was because of the OracleBlob parameter. I didn't think I needed it, and thought I could just do something like:

    DataSet ds = new DataSet();
    OracleCommand cmd = new OracleCommand(strQuery, conn);
    OracleDataAdapter oraAdpt = new OracleDataAdapter(cmd);
    oraAdpt.Fill(ds)
    
    if (ds.Tables[0].Rows.Count > 0)
    {
        byte[] myArray = (bytes)ds.Tables[0]["MY_BLOB_COLUMN"];
    }
    

    How wrong I was! To actually get the real bytes in that blob, I needed to actually read that result into an OracleBlob object. Instead of filling a dataset/datatable, I did this:

    OracleBlob oBlob = null;
    byte[] myArray = null;
    OracleCommand cmd = new OracleCommand(strQuery, conn);
    OracleDataReader result = cmd.ExecuteReader();
    result.Read();
    
    if (result.HasRows)
    {
        oBlob = result.GetOracleBlob(0);
        myArray = new byte[oBlob.Length];
        oBlob.Read(array, 0, Convert.ToInt32(myArray.Length));
        oBlob.Erase();
        oBlob.Close();
        oBlob.Dispose();
    }
    

    Then, I could take myArray and do this:

    if (myArray != null)
    {
       if (myArray.Length > 0)
       {
           MyImage.Source = LoadBitmapFromBytes(myArray);
       }
    }
    

    And my revised LoadBitmapFromBytes function from the other answer:

    public static BitmapImage LoadBitmapFromBytes(byte[] bytes)
    {
        var image = new BitmapImage();
        using (var stream = new MemoryStream(bytes))
        {
            stream.Seek(0, SeekOrigin.Begin);
            image.BeginInit();
            image.StreamSource = stream;
            image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = null;
            image.EndInit();
        }
    
        return image;
    }
    

提交回复
热议问题