Search  
Always will be ready notify the world about expectations as easy as possible: job change page
Jul 15

Convert images to WebP in C# .NET 7

Convert images to WebP in C# .NET 7
Source:
Views:
1218

I recently migrated this blog from WordPress to a custom Nuxt site. I moved from WordPress to have more control over the blog and not have to rely on plugins to do everything. It’s worked out really well but there is one plugin I do miss: Smush ☹️

Performance is really important for all websites. It improves user experience and has a big impact on SEO rankings. The standard tool for measuring performance is Google Lighthouse. It’s what I used when I migrated this blog. Lighthouse scores your performance out of 100 and gives suggestions on how to improve it.

Images are often the biggest assets in a blog post and can really damage the Lighthouse score. This is where Smush comes in. Smush does a great job of automatically optimizing your blog’s images. Optimized images helps your blog load quickly and get a good Lighthouse score.

Now that I don’t have access to Smush on my custom Nuxt site I have to optimize the images myself…

An improvement that Lighthouse always suggests is to convert all images to the WebP format. WebP is a replacement for Jpeg, Png and Gif images. It has a much smaller file size which is why Lighthouse suggests it. Converting all my images to it should give the blog a nice boast 🚀

All the images on this blog are served by an Azure function and cached via Cloudflare. This means I can convert them to WebP on the fly inside the function.

Anyway that’s a really long explanation for just a couple lines of code 😅

All you need is the SixLabors.ImageSharp Nuget package and some code like this:

var imageBytes = await File.ReadAllBytesAsync("your-image.jpg");

using var inStream = new MemoryStream(imageBytes);
            
using var myImage = await Image.LoadAsync(inStream);

using var outStream = new MemoryStream();
            
await myImage.SaveAsync(outStream, new WebpEncoder());

return new FileContentResult(outStream.ToArray(), "image/webp");

WebP file size example

Lighthouse isn’t lying BTW, the difference in file size is actually really good…

For example, this screenshot of my blog home page goes from 622KB as a PNG to just 72KB as a WebP 👀

Similar
24 марта
Автор: Ivan Kolesov
Фреймворк Angular используется при создании SPA и предлагает большое количество инструментов как для создания, непосредственно, элементов интерфейса, так и CLI для создания и управления структурой файлов, относящихся к приложению. Для создания проекта с использованием библиотеки Angular, официальный сайт предлагает нам...
28 июня 2021 г.
Автор: MaxRokatansky
Эта статья раскрывает концепции Middleware в ASP.NET Core. К концу этой статьи вы получите четкое представление о следующих моментах: Что такое Middleware? Почему порядок расположения Middleware имеет значение? Методы Run, Use и Map. Как создать собственное Middleware? Как реализовать просмотр...
Jul 16, 2020
Author: Kannan Eswar
In this blog, I am going to provide a walkthrough on developing REST APIs using ASP.NET Core 3.1, connecting with existing databases using Entity Framework, creating a JWT token, and securing APIs. I am going to develop a sample application...
Aug 23, 2022
Author: Luis Rodrigues
Suppose we are building a web api that contains a route to send notification messages to other systems. For security matters, before sending any notification message, we need to provide some credentials to these systems to they accept our messages....
Send message
Email
Your name
*Message


© 1999–2024 WebDynamics
1980–... Sergey Drozdov
Area of interests: .NET Framework | .NET Core | C# | ASP.NET | Windows Forms | WPF | HTML5 | CSS3 | jQuery | AJAX | Angular | React | MS SQL Server | Transact-SQL | ADO.NET | Entity Framework | IIS | OOP | OOA | OOD | WCF | WPF | MSMQ | MVC | MVP | MVVM | Design Patterns | Enterprise Architecture | Scrum | Kanban