将BitmapImage转换为byte[]

42

我有一个在WPF应用程序中使用的BitmapImage,我希望将其转换为字节数组保存到数据库中(我猜这是最好的方法),如何进行此转换?

或者,有没有更好的方法将BitmapImage(或其基类之一BitmapSourceImageSource)保存到数据存储库中?

5个回答

71

要将其转换为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 列作为 MS SQL 支持该数据类型,但您仍需要以某种方式转换 BitmapImage。


如果我使用UriSource加载图像,则此方法有效,但是如果我从内存流中加载它,在encoder.Save(ms)处,我会得到“System.InvalidOperationException”中抛出的异常,PresentationCore.dll中未处理的类型为'System.InvalidOperationException'的异常发生了 由于对象的当前状态而无效。ms的一些属性显示为'System.InvalidOperationException'。 - Tommy
1
@Tommy 这听起来像是你面临的另一个问题,可能只是在转换过程中突然出现了,因为它应该可以正常工作...也许你可以创建一个新的问题,包括你的代码以重现这个问题,并在这里评论一个链接? - Christoph Fink
@Christopher 非常感谢。我已经在这里发布了(https://stackoverflow.com/questions/69812386/saving-a-bitmapimage-to-file-works-when-the-image-has-been-imported-from-file-b) - Tommy

6
您需要使用从BitmapEncoder(如BmpBitmapEncoder)派生的类的实例,并调用Save方法将BitmapSource保存到Stream中。

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


1
你能提供一份代码示例吗?假设为简单起见,我想要PNG格式(这是加载到BitmapImage中的格式)。 - SoManyGoblins

-1

将其写入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;
}

3
如果你正在使用UriSource加载图片,我认为这种方法行不通,但我不确定... - Christoph Fink
@chrfin 嗯,不知道,我还没有尝试过。但应该对他的WPF应用程序没问题。 - Muad'Dib
我的BitmapImage上的StreamSource属性为空,有什么想法吗? - SoManyGoblins
@So:因为你没有从流中加载它。这对你来说行不通。 - user7116
@ChrFin:是的,你说得对。如果我们使用UriSource,StreamSource将为空。 - Venugopal M

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


-7

只需使用MemoryStream。


byte[] data = null;

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



你忘记了一些步骤... 你需要使用一个编码器。 - memory of a dream

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接