2012-02-15 68 views
0

我正在使用C#和WPF。我想在運行時添加一個PNG和JPG到圖像源,但我得到的是說,一個例外:如何添加PNG和JPG在runtıme

Can not implicitly add convert type string to Sytem.Windows.Media.imageSource

using System.IO;      //for : input - output 
using Microsoft.Win32;    //For : OpenFileDialog/SaveFileDialog 
using System.Windows.Media.Imaging; //For : BitmapImage etc etc 




<Image x:Name="img" Margin="9,13.5,6,0.5" Source="Laugh.ico"> 


private void ac(object sender, RoutedEventArgs args) 
    {  
    OpenFileDialog dlg = new OpenFileDialog(); 
    // Configure open file dialog box 
    dlg.FileName = "Document"; // Default file name 
    dlg.DefaultExt = ".PNG"; // Default file extension 
    dlg.Filter = " (.PNG)|*.PNG"; // Filter files by extension 

    // Show open file dialog box 
    Nullable<bool> result = dlg.ShowDialog(); 

    // Process open file dialog box results 
    if (result == true) 
    { 
    // Open document 
    string filename = dlg.FileName; 
    img.Source=filename; 
    } 

    } 

回答

3

很抱歉,但你可能已經注意到,該代碼甚至不會編譯。您無法將圖像源設置爲文件名

img.Source = filename 

查看reference

試試這個:

img.Source = new BitmapImage(new Uri(filename)); 
+0

這項工作極大的THX Zortkun THX這麼多;) – 2012-02-15 18:56:41

0

我認爲主要路線是:

img.Source=filename 

這應該是這樣的:

BitmapImage bi= new BitmapImage(); 
bi.BeginInit(); 
bi.UriSource = new Uri(filename, UriKind.Relative); 
bi.EndInit(); 
img.Source = bi; 

當你有實際讀取的圖像文件從磁盤進入。

+0

IMG = Image.FromFile(文件名); 'System.Windows.Controls.Image'不包含'FromFile'的定義 – 2012-02-15 18:54:05

+0

更正了我自己 - 對不起 – BeRecursive 2012-02-15 18:57:39

0

不知道這是否會爲圖像的工作計劃之外,但你可以嘗試:

Uri uri = new Uri(dlg.File.FullName, UriKind.RelativeOrAbsolute); 
ImageSource imgSource = new BitmapImage(uri); 
img.Source = imgSource;