Share via

How to display avif image in Blazor page?

Jason Peng 20 Reputation points
Dec 25, 2023, 6:08 AM

AVIF images are gaining popular because of its super advantage over jpg/png etc, but avif images cannot be displayed in Blazor-based web page. For example, among the following three image tags, (2) is webp format that can be displayed; (1) and (3) are avif format that failed to display in razor page. If move the avif image to a pure html page, they can be displayed in browser such as Chrome or Safari.

(1) <img src="/imgx/art/40-1.avif" alt="avif" />

(2) <img src="/imgx/art/40-1.webp" alt="webp" />

(3) see below

<picture>    
    <source media="(min-width:768)" srcset="/imgx/art/40-1.avif" type="image/avif" width="50%" height="auto">       
    <img src="/imgx/art/40-1.webp" alt="My blog" width="100%" height="auto">
</picture>

Question: How to make Blazor based web page display avif image at least in popular browsers? How to make Visual Studio 2022 able to show avif image just like jpg/png/webp?

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,672 questions
0 comments No comments
{count} votes

Accepted answer
  1. Brando Zhang-MSFT 3,956 Reputation points Microsoft External Staff
    Dec 25, 2023, 7:51 AM

    Hi @Jason Peng,

    The asp.net core server does not recognize AVIF as an image type so it cannot correctly render it on the page even if the browser can support it.

    So you need to modify the StaticFiles middleware to enable the support for it.

    More details, you could refer to below codes:

    // Set up custom content types - associating file extension to MIME type
    var provider = new FileExtensionContentTypeProvider();
    // Add new mappings
    provider.Mappings[".avif"] = "image/avif";
    
    app.UseStaticFiles(new StaticFileOptions
    {
        ContentTypeProvider = provider
    });
    

    Result:

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.