如何使用资源中的图像?

时间:2019-06-30 08:07:09

标签: c# wpf rectangles

我想使用路径从程序资源映像,而不是使用Windows的完整路径。

tlo.Fill = new ImageBrush
{
  ImageSource = new BitmapImage(new Uri(@"D:\Willie\Documents\ColorTester\ColorTester\Resources\1.jpg", UriKind.Absolute))
};

我想使用这样的路径:

ImageSource = new BitmapImage(new Uri("ColorTester.Resources.1.jpg"));

有人可以帮我吗,因为当我尝试使用它时,Visual Studio会抛出异常“ System.UriFormatException”?

2 个答案:

答案 0 :(得分:0)

我不知道图像的正确路径,如果您的项目下有一个名为Resources的文件夹,并且图像位于其中,则可以按以下方式处理它们:

ImageSource = new BitmapImage(new Uri("/Resources/1.jpg", UriKind.Relative));

如果图像位于UserControl内,并且您想在其他项目中使用它,请按照以下方式处理它:

ImageSource = new BitmapImage(new Uri("pack://application:,,,/{YourAssemblyWhereResourceIsLocated};component/Resources/1.jpg"));

有用的链接:

答案 1 :(得分:-1)

选项1

如果您还没有做的话,您需要做的是单击“项目”菜单,然后转到类似于“ your_project_name_here 属性”的选项。打开后,单击资源选项卡。点击“添加资源”->“添加现有文件”,添加您想要的任何图像。

Picture of the resources tab

如果您使用的是Windows窗体,则可以执行以下操作:

var bitmap = new Bitmap(YourAppName.Properties.Resources.1);

您还可以在此处查看如何将位图转换为BitmapImage:Converting BitmapImage to Bitmap and vice versa

选项2

但是,如果您只是将图像复制并粘贴到资源文件夹中,则可以执行以下操作:

ImageSource = new BitmapImage(new Uri(@"pack://application:,,,/Resources/1.jpg"));

您可以将“ 1.jpg”替换为其他任何文件。