首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 媒体动画 > CAD教程 >

怎么取/Image/Tip/Logo.jpg的Stream

2012-03-11 
如何取/Image/Tip/Logo.jpg的Stream如题,图片我设置为了“内容”我想把这张图片以Stream的方式读出来。请问怎

如何取/Image/Tip/Logo.jpg的Stream
如题,图片我设置为了“内容”
我想把这张图片以Stream的方式读出来。请问怎么实现?


[解决办法]
不能使用 File.OpenRead() ,而是要使用 Application.GetResourceStream()

Silverlight 3.0 官方文档的例子:

C# code
using System.IO; // Streamusing System.Windows; // Applicationusing System.Windows.Controls; // TextBlock, Imageusing System.Windows.Media.Imaging; // BitmapImageusing System.Windows.Resources; // StreamResourceInfonamespace SilverlightApplication{    public partial class PageShort : UserControl    {        public PageShort()        {            InitializeComponent();            // Load image resource files included in the application package             // and resources that are embedded in assemblies included in the            // application package.            // Load an image resource file embedded in the application assembly.            Image img1 = LoadImage(                "/SilverlightApplication;component/EmbeddedInApplicationAssembly.png");            this.stackPanel.Children.Add(img1);            // Load an image resource file included the application package.            Image img2 = LoadImage("IncludedInApplicationPackage.png");            this.stackPanel.Children.Add(img2);            // Load an image resource file embedded in a library assembly,             // which is included in the application package.            Image img3 = LoadImage(                "/SilverlightLibrary;component/EmbeddedInLibraryAssembly.png");            this.stackPanel.Children.Add(img3);        }        public Image LoadImage(string relativeUriString)        {            // Get the image stream at the specified URI that            // is relative to the application package root.            Uri uri = new Uri(relativeUriString, UriKind.Relative);            StreamResourceInfo sri = Application.GetResourceStream(uri);            // Convert the stream to an Image object.            BitmapImage bi = new BitmapImage();            bi.SetSource(sri.Stream);            Image img = new Image();            img.Source = bi;            return img;        }    }}
[解决办法]
如果想使用OpenFile的方式打开图片可以使用以下代码就可以实现。


C# code
private void Button_Click_Load_Image(object sender, RoutedEventArgs e){    OpenFileDialog ofd = new OpenFileDialog();    ofd.Filter = "PNG Files (*.png;*.png)|*.png;*.png | All Files (*.*)|*.*";    ofd.FilterIndex = 1;        if (true == ofd.ShowDialog())    {        System.IO.Stream stream = ofd.File.OpenRead();        BitmapImage bi = new BitmapImage();       bi.SetSource(stream);        MyImage.Source = bi;        stream.Close();    }} 

热点排行