0

我有一个WPF Image从图片对话框分配的源;

this.imgProduct.Source = new BitmapImage(new Uri(op.FileName)); 

如何检索源,将其转换为byte array并将其保存到database?

谢谢

4

2 回答 2

0

您必须将 BitmapImage 转换为 byte[] 然后将其保存到数据库中。

var imageSource = this.imgProduct.Source as BitmapImage;
var stream = imageSource.StreamSource;
Byte[] buffer = null;

if (stream != null && stream.Length > 0)
{
    using (BinaryReader br = new BinaryReader(stream))
    {
        buffer = br.ReadBytes((Int32)stream.Length);
    }
}

// write buffer to the database

PS我没有测试过代码,但我认为它有效!

于 2012-10-17T04:21:01.177 回答
0

只要您可以访问其中的图像文件,op.FileName就可以很容易地通过例如获取文件内容

byte[] imageBuffer = File.ReadAllBytes(op.FileName);

如果图像是从文件 Uri 加载的(如您的示例中所示),您也可以这样做:

byte[] imageBuffer = File.ReadAllBytes(image.UriSource.AbsolutePath);

如果您只有 BitmapImage 而没有有关从中加载它的文件的信息(例如,当它从临时文件或 Web 资源加载时),则必须通过 WPFs BitmapEncoders之一对其进行编码:

byte[] imageBuffer;
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));

using (MemoryStream stream = new MemoryStream())
{
    encoder.Save(stream);
    imageBuffer = stream.GetBuffer();
}
于 2012-10-17T07:14:13.527 回答