在WPF中,如何在代码后台更改图像源?

47

我需要动态设置图片来源,需要注意的是我的图片存储在网络上某个位置,以下是我的代码:

BitmapImage logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri(@"pack://application:,,,\\myserver\\folder1\\Customer Data\\sample.png");
logo.EndInit(); // Getting the exception here
ImageViewer1.Source = logo;

异常:

URI 前缀未被识别

6个回答

81

以上的解决方案都对我不起作用,但这个可以:

myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative));

4
+1 是因为它非常新。对我来说,这也是唯一有效的方法。 - Totumus Maximus
5
请注意,这种方法在UWP中不起作用,因为UWP似乎只接受绝对URI。以下是如何实现:myImage.Source = new BitmapImage (new Uri (new Uri (Directory.GetCurrentDirectory(), UriKind.Absolute), new Uri (@"/Images/foo.png", UriKind.Relative))); - Thought
这可能并不是回答问题的方法,但由于我的问题带我来到这里,这个答案对我有用。 - Rachel Martin
我遇到的唯一问题是,PNG 的透明度丢失了,似乎没有办法恢复它... - frankenapps

77

你只需要一行代码:

ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png"));

5
您在这里使用的pack语法是针对应用程序中作为资源包含的图像,而不是文件系统中的松散文件。
您只需传递实际路径到UriSource即可:
logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");

4

对我来说,这些方法都不起作用,因为我需要从文件夹中拉取图像而不是将其添加到应用程序中。

下面的代码可以解决问题:

TestImage.Source = GetImage("/Content/Images/test.png")

private static BitmapImage GetImage(string imageUri)
{
    var bitmapImage = new BitmapImage();
    
    bitmapImage.BeginInit();
    bitmapImage.UriSource = new Uri("pack://siteoforigin:,,,/" + imageUri,             UriKind.RelativeOrAbsolute);
    bitmapImage.EndInit();
    
    return bitmapImage;
} 

0
我的NET 7项目文件如下所示。
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net7.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

  <ItemGroup>
    <None Remove="images\RuntimePicture.png" />
  </ItemGroup>

  <ItemGroup>
    <Resource Include="images\RuntimePicture.png">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Resource>
  </ItemGroup>


</Project>

根据proj文件显示,我在一个名为images的文件夹中有一张图片。 ctor的后台代码如下所示。
public MainWindow()
{
    InitializeComponent();
    ImageEx.Source = new BitmapImage(new Uri(@"/images/RuntimePicture.png", UriKind.Relative));

}

主窗口的XAML代码如下所示。
<Image x:Name="ImageEx" Height="300" Width="500" />

最后,右键单击PNG文件,在文件属性窗口中确保构建操作设置为资源

-4

你们都错了!为什么?因为你只需要这段代码就可以工作:

(image View) / C# Img is : your Image box

保持原样,不要更改("ms-appx:///),这是代码而不是你的应用程序名称 Images是你项目中的文件夹,你可以更改它。 dog.png是你文件夹中的文件,就像我做的那样,我的文件夹名为'Images',文件名为'dog.png' 所以URI是:"ms-appx:///Images/dog.png" 我的代码:


private void Button_Click(object sender, RoutedEventArgs e)
    {
         img.Source = new BitmapImage(new Uri("ms-appx:///Images/dog.png"));
    }

1
我认为你们都错了,因为你们没有提供一个完整的工作示例。假设读者知道在代码中放置这些片段。 - Alex Jansen
回答开始时的轻率言论是不必要的。只需要完整可用的答案,并附上使用说明即可。 - JoeTomks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接