【问题标题】:Append image to image.source in wpf将图像附加到 wpf 中的 image.source
【发布时间】:2016-11-11 04:56:54
【问题描述】:

我正在尝试将图像附加到图像源,但执行代码后图像未显示在我的页面中。

代码:

 Bitmap bmp = (Bitmap)data.img;
 MemoryStream ms = new MemoryStream();
 bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
 ms.Position = 0;
 BitmapImage bi = new BitmapImage();
 bi.BeginInit();
 bi.StreamSource = ms;
 bi.EndInit();
 imgPhoto.Source = bi;

这是我想附加到 imhPhoto.Source 的 data.img 规范。

【问题讨论】:

    标签: c# .net wpf winforms


    【解决方案1】:

    在解决了这个问题之后,这个问题的解决方案是:

    调用函数获取 BitmapImage 并将其保存在 photo 变量中,如下所示:

    BitmapImage photo = byteToImage(byte[] buffer)
    

    此函数将字节转换为位图图像

    public BitmapImage byteToImage(byte[] buffer)
    {
    
     using(var ms = new MemoryStream(buffer))
     {
       var image = new BitmapImage();
       image.BeginInit();
       image.CacheOption = BitmapCacheOption.OnLoad;
       image.StreamSource =  ms;
       image.EndInit();
     }
    
     return image;
    }
    

    最后,将转换后的照片附加到图像源,如下所示:

    imgPhoto.Source = photo;
    

    【讨论】:

      【解决方案2】:

      您可以像这样分配路径。

        //for App folder path
                  //var path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)+"\\Image\\pic.jpg";
      
                  //for machine path
                  var path = @"C:\Users\User1\Pictures\pic.jpg";
      
                  Bitmap bmp = new Bitmap(path);
                  MemoryStream ms = new MemoryStream();
                  bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                  ms.Position = 0;
                  BitmapImage bi = new BitmapImage();
                  bi.BeginInit();
                  bi.StreamSource = ms;
                  bi.EndInit();
                  imgPhoto.Source = bi;
      

      【讨论】:

        【解决方案3】:

        如果这解决了你的问题:

        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(@"g:\screenshot.png");
        
        BitmapImage bi = new BitmapImage();
        bi.BeginInit();
        
        MemoryStream ms = new MemoryStream();
        bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        ms.Position = 0;            
        
        bi.StreamSource = ms;
        bi.EndInit();
        
        imgPhoto.Source = bi;
        

        【讨论】:

        • 上面写着imgPhoto.Source.Metadata threw an exception of type System.NotSupportedException 并且图像还没有显示..
        • 你能看一下附图中的RawFormat吗?我认为这是主要问题,但我不知道如何让它知道格式
        猜你喜欢
        • 2015-03-20
        • 2015-05-19
        • 2011-06-05
        • 2011-08-07
        • 1970-01-01
        • 1970-01-01
        • 2013-11-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多