【问题标题】:Save Image source to database将图像源保存到数据库
【发布时间】:2012-10-17 15:25:52
【问题描述】:

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

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

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

谢谢

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    您必须将 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
    

    附:我还没有测试过代码,但我认为它可以工作!

    【讨论】:

    • StreamSource 将是 null,因为图像是从 Uri 加载的。
    【解决方案2】:

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

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

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

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

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

    byte[] imageBuffer;
    PngBitmapEncoder encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(image));
    
    using (MemoryStream stream = new MemoryStream())
    {
        encoder.Save(stream);
        imageBuffer = stream.GetBuffer();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-10
      • 2019-06-27
      • 1970-01-01
      • 2020-03-07
      • 2020-04-07
      相关资源
      最近更新 更多