【问题标题】:Image source UriKind图片来源 UriKind
【发布时间】:2012-05-18 14:50:21
【问题描述】:

我有一个名为“xx”的项目。 我创建了一个具有此路径的文件夹“图像”: 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;
}

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

【问题讨论】:

    标签: c# wpf image uri


    【解决方案1】:

    您需要将1.jpg 添加到您的项目中的images 文件夹和1.jpgset the Properties资源。要加载资源,请使用 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;
    }
    

    【讨论】:

    • 我从窗口资源管理器中手动添加了这个文件夹和 1.jpg,而不是从我的项目的解决方案中
    • 最佳实践是将其添加到您的项目中并设置始终复制。这样,它将始终被复制到输出(调试/发布)文件夹中,并由源代码控制管理。
    • System.Windows.Controls.Image 不包含静态方法 (FromFile) 注意:我的项目是 wpf 项目
    • 您的问题未标记为 WPF,很抱歉造成混淆。请参阅上面的修改。
    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-27
      • 2015-05-02
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-17
      • 2011-02-19
      相关资源
      最近更新 更多