Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed images in .net Maui nuget package?

Tags:

nuget

maui

I have a library project in .NET Maui 7.

Within the library I'm creating some custom views that have some images. The library project is compiled as a nuget package.

The images are added the resource folder of the library project with Build action as MauiImage as follows:

enter image description here

When using the Nuget package in another project, the images are not shown in the custom views. In order to make them show, I need to add them to the new project. It's like the images are not included in the Nuget Package.

How can I embed the images in the nuget package?

like image 378
Thomas Carlton Avatar asked Sep 20 '25 08:09

Thomas Carlton


1 Answers

I tried suggesting an edit to @Ramaraj answer but was unable to do it because of the edit queue limit. So, I am writing a new answer instead.

Instead of using MauiImage in the project file, we have to use None for pack to work. The same logic goes for MauiAssets and other Maui resource files.

Here is the complete solution:

  1. Create a My.NuGet.Package.Id.targets (note the filename has to be the same as your actual package id) with all the image references.
<!-- Rest of the file -->
  <ItemGroup>
    <MauiImage Include="$(MSBuildThisFileDirectory)\Images\check.png" />
  </ItemGroup>
</Project>
  1. Ensure the targets file and the Maui resource files (in this case check.png) are embedded in the appropriate folder within the Nuget package of our library project. For this, we use Pack and PackagePath as follows in the csproj file:
<!-- Rest of the file -->
<ItemGroup>
  <None Include="My.NuGet.Package.Id.targets" Pack="True" PackagePath="buildTransitive\" />
</ItemGroup>
<ItemGroup>
  <None Include="Resources\Images\check.png" Pack="True" PackagePath="buildTransitive\Images\" />
</ItemGroup>
<!-- Rest of the file -->

NOTE: The subtle change from @Ramaraj's answer is that we changed the build action from MauiImage to None. This is required for Pack to work.

You can get more information about buildTransitive folder and other build folders in this Microsoft documentation.

like image 81
Shantanu Methikar Avatar answered Sep 23 '25 07:09

Shantanu Methikar