40

我有一个BitmapImage在 WPF 应用程序中使用的,稍后我想将它作为字节数组保存到数据库中(我想这是最好的方法),我该如何执行这种转换?

或者,是否有更好的方法将 a BitmapImage(或其任何基类,BitmapSourceImageSource)保存到数据存储库?

4

5 回答 5

68

要转换为 byte[],您可以使用 MemoryStream:

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

正如 casperOne 所说,您可以使用您喜欢的任何 BitmapEncoder,而不是 JpegBitmapEncoder。

如果您使用的是 MS SQL,您也可以使用image-Column,因为 MS SQL 支持该数据类型,但您仍然需要以某种方式转换 BitmapImage。

于 2011-07-06T14:05:34.337 回答
6

您将不得不使用派生自BitmapEncoder(例如BmpBitmapEncoder)的类的实例,并调用该Save方法BitmapSourceStream.

您将根据要保存图像的格式选择特定的编码器。

于 2011-07-06T14:13:22.090 回答
-1

将其写入 a MemoryStream,然后您可以从那里访问字节。有点像这样:

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;
}
于 2011-07-06T14:04:51.223 回答
-2

您可以给出位图的格式:

Image bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics.FromImage(bmp).CopyFromScreen(new Point(0, 0), new Point(0, 0), Screen.PrimaryScreen.Bounds.Size);

MemoryStream m = new MemoryStream();
bmp.Save(m, System.Drawing.Imaging.ImageFormat.Png);
byte[] imageBytes = m.ToArray();
string base64String = Convert.ToBase64String(imageBytes);

于 2021-06-24T07:30:23.197 回答
-7

只需使用 MemoryStream。


byte[] data = null;

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


于 2011-07-06T14:08:23.373 回答