如何使用c#wpf应用程序流式传输图像

时间:2014-06-25 05:05:42

标签: c# wpf

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Web; 
using System.IO;

namespace WpfApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        public MainWindow(Stream stream)
        {
            InitializeComponent();
            String path = @"C:\Users\Public\Pictures\Sample Pictures\Jellyfish.jpg";
            var image = new BitmapImage();
            try
            {
                image.BeginInit();
                image.StreamSource = stream;
                image.EndInit();
                using (Stream bmpStream = System.IO.File.Open(path,System.IO.FileMode.Open))
                {
                    Image im = Image.FromStream(bmpStream);
                    //Bitmap img = (Bitmap)Image.FromFile("aa.gif", true);
                    //var im = ImageFromStream(bmpStream);
                    grid1.Background = new ImageBrush(new BitmapImage(new Uri(@"im")));
                }
                // return image;
            }

            catch (Exception a)
            {
                // return image;
            }
        }
        public void Window_Loaded(object sender, RoutedEventArgs e)
        {


        }


     }

}

我使用上面的代码将jpg图像作为位图流式传输,并使用c#将其设置为网格,但Image im = Image.FromStream(bmpStream);显示错误。有人可以指导我如何将jpg图像作为位图流并设置为网格吗?

1 个答案:

答案 0 :(得分:2)

WPF处理和显示图像的方式与WinForms的方式略有不同。 大多数图像显示“事物”需要ImageSource,您必须搜索正确的“事物”。 在这种情况下,你应该能够使用BitmapImage - 但是我最后一次检查这个时需要更加小心地正确显示字节流的内容。

此代码段显示了您应该如何正常工作BitmapImage

private static BitmapImage LoadImage(Stream stream)
{
    // assumes that the streams position is at the beginning
    // for example if you use a memory stream you might need to point it to 0 first
    var image = new BitmapImage();

    image.BeginInit();
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.StreamSource = stream;
    image.EndInit();

    image.Freeze();
    return image;
}

正如您所看到的,您需要告诉图片在加载后立即使用该流(或者您可以使用ObjectDisposedException等令人讨厌的内容。

您可以将返回的对象用作Image的源属性。

所以我认为你要找的是这样的:

public MainWindow(Stream stream)
{
    InitializeComponent();
    grid1.Background = new ImageBrush(LoadImage(stream));
}