Image source UriKind

為{幸葍}努か 提交于 2019-12-23 17:27:14

问题


I have a project it's name is 'xx'. I create a folder "images" that have this path : xx\bin\Debug\images\

images contain only one photo it's name is "1.jpg" the MainWindow contain Image control; I set this code to load the image source but it doesn't work why ??:

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

How can I load the Image source by code ?? Thanks in advance :)


回答1:


You need to add 1.jpg to your project in the images folder and set the Properties of 1.jpg to Resource. To load the resource, use the packURI conventions.

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



回答2:


Try this

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


来源:https://stackoverflow.com/questions/10654861/image-source-urikind

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!