图像源UriKind

时间:2012-05-18 14:50:21

标签: c# wpf image uri

我有一个项目,它的名字是'xx'。 我创建了一个具有此路径的文件夹“images”: XX \ BIN \调试\图像\

图片只包含一张照片,其名称为“1.jpg” MainWindow包含图像控件; 我设置此代码来加载图像源,但它不起作用??:

private void Image_MouseDown(object sender, MouseButtonEventArgs e)
{
    Image i = sender as Image; ;
    BitmapImage b = new BitmapImage(new Uri(@"images\1.jpg",UriKind.Relative));
    i.Source=b;
}

如何通过代码加载图像源? 在此先感谢:)

2 个答案:

答案 0 :(得分:2)

您需要在1.jpg文件夹中将images添加到1.jpg private void Image_MouseDown(object sender, MouseButtonEventArgs e) { Image i = sender as Image; ; BitmapImage b = new BitmapImage(new Uri(@"pack://application:,,,/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/" + "Images/1.jpg", UriKind.Absolute)); i.Source=b; } 资源set the Properties。要加载资源,请使用packURI约定。

{{1}}

答案 1 :(得分:0)

试试这个

public void Image_MouseDown(object sender, RoutedEventArgs e)
{
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.InitialDirectory = "c:\\";
    dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";
    dlg.RestoreDirectory = true;
    Nullable<bool> result = dlg.ShowDialog();                        

    if (result == true)
    {
        BitmapImage bitmap = new BitmapImage();
        Image img = sender as Image;
        bitmap.BeginInit();
        bitmap.UriSource = new Uri(dlg.FileName);
        bitmap.EndInit();
        img.Source = bitmap;
    }
}