我有一个BitmapImage
在 WPF 应用程序中使用的,稍后我想将它作为字节数组保存到数据库中(我想这是最好的方法),我该如何执行这种转换?
或者,是否有更好的方法将 a BitmapImage
(或其任何基类,BitmapSource
或ImageSource
)保存到数据存储库?
我有一个BitmapImage
在 WPF 应用程序中使用的,稍后我想将它作为字节数组保存到数据库中(我想这是最好的方法),我该如何执行这种转换?
或者,是否有更好的方法将 a BitmapImage
(或其任何基类,BitmapSource
或ImageSource
)保存到数据存储库?
要转换为 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。
您将不得不使用派生自BitmapEncoder
(例如BmpBitmapEncoder
)的类的实例,并调用该Save
方法BitmapSource
将Stream
.
您将根据要保存图像的格式选择特定的编码器。
将其写入 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;
}
您可以给出位图的格式:
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);
只需使用 MemoryStream。
byte[] data = null;
using(MemoryStream ms = new MemoryStream())
{
bitmapImage.Save(ms);
data = ms.ToArray();
}