BitmapImage to byte[]

让人想犯罪 __ 提交于 2019-11-26 09:39:03

问题


I have a BitmapImage that I\'m using in a WPF application, I later want to save it to a database as a byte array (I guess it\'s the best way), how can I perform this conversion?

Or, alternatively, is there a better way to save a BitmapImage (or any of its base classes, BitmapSource or ImageSource) to a data repository?


回答1:


To convert to a byte[] you can use a MemoryStream:

byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
using(MemoryStream ms = new MemoryStream())
{
    encoder.Save(ms);
    data = ms.ToArray();
}

Instead of the JpegBitmapEncoder you can use whatever BitmapEncoder you like as casperOne said.

If you are using MS SQL you could also use a image-Column as MS SQL supports that datatype, but you still would need to convert the BitmapImage somehow.




回答2:


You will have to use an instance of a class that derives from BitmapEncoder (such as BmpBitmapEncoder) and call the Save method to save the BitmapSource to a Stream.

You would choose the specific encoder depending on the format you want to save the image in.




回答3:


write it to a MemoryStream, then you can access the bytes from there. something kinda like this:

public Byte[] ImageToByte(BitmapImage imageSource)
{
    Stream stream = imageSource.StreamSource;
    Byte[] buffer = null;
    if (stream != null && stream.Length > 0)
    {
        using (BinaryReader br = new BinaryReader(stream))
        {
            buffer = br.ReadBytes((Int32)stream.Length);
        }
    }

    return buffer;
}



回答4:


Just use a MemoryStream.


byte[] data = null;

using(MemoryStream ms = new MemoryStream())
{
    bitmapImage.Save(ms);
    data = ms.ToArray();
}




来源:https://stackoverflow.com/questions/6597676/bitmapimage-to-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!