如何在运行时添加PNG和JPG
本文关键字:PNG JPG 添加 运行时 | 更新日期: 2023-09-27 18:24:39
我正在使用C#和WPF。我想在runtıme上添加一个PNG和JPG到图像源,但我得到了一个例外,上面写着:
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;
}
}
很抱歉,但正如您可能已经注意到的,该代码甚至无法编译。不能将图像源设置为文件名
img.Source = filename
看看参考资料。
试试这个:
img.Source = new BitmapImage(new Uri(filename));
不确定这是否适用于程序外的图像,但您可以尝试:
Uri uri = new Uri(dlg.File.FullName, UriKind.RelativeOrAbsolute);
ImageSource imgSource = new BitmapImage(uri);
img.Source = imgSource;
我认为关键行是:
img.Source=filename
应该是这样的:
BitmapImage bi= new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(filename, UriKind.Relative);
bi.EndInit();
img.Source = bi;
因为您必须实际从磁盘中读取图像文件。