图片来源 UriKind

本文关键字:UriKind | 更新日期: 2023-09-27 18:34:40

我有一个项目,它的名字是'xx'。我创建了一个具有此路径的文件夹"图像":xx''bin''调试''图像''

图片只包含一张照片,它的名字是"1.jpg"主窗口包含图像控件;我设置此代码以加载图像源,但它不起作用,为什么??:

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;
}

如何通过代码加载图像源?提前致谢:)

图片来源 UriKind

您需要

1.jpg添加到项目中的images文件夹中,并将1.jpg的属性设置为资源。若要加载资源,请使用 packURI 约定。

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;
}

试试这个

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;
    }
}