Поиск  
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
Источник:
Просмотров:
2677

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 👀

Похожее
Jul 21
Author: Henrik Arent
Choosing between .NET Core and .NET Framework is a crucial decision for your business. Your choice between them can significantly impact the smoothness of your software projects and the success of your business. Both of these platforms have their own...
Sep 10, 2023
Author: Sriram Kumar Mannava
In a situation where we need to modify our API’s structure or functionality while ensuring that existing API clients remain unaffected, the solution is versioning. We can designate our current APIs as the older version and introduce all intended changes...
Nov 9, 2020
Author: Akhil Mittal
Microservices The term microservices portrays a software development style that has grown from contemporary trends to set up practices that are meant to increase the speed and efficiency of developing and managing software solutions at scale. Microservices is more about...
Oct 24, 2022
Author: Chandan Das
For as long as web applications have been around, full-stack developers have had to work with different sets of technologies for the front and backend. For instance, a developer would use something like Angular for the frontend and Express.js for...
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS
Если вам понравился этот сайт и вы хотите меня поддержать, вы можете
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник
Performance review, ачивки и погоня за повышением грейда — что может причинить боль сотруднику IT-компании?
GraphQL решает кучу проблем — рассказываем, за что мы его любим
Разбираемся с middleware в ASP.NET Core
Как избавиться от прокрастинации до того, как она разрушит вашу карьеру
Функции и хранимые процедуры в PostgreSQL: зачем нужны и как применять в реальных примерах
Разрабы работают медленно и дорого — и люди считают нас лентяями. Просто в разработке всё сложно
Using a сustom PagedList class for Generic Pagination in .NET Core
Четыре типажа программистов
Интернет вещей — а что это?
LinkedIn: Sergey Drozdov
Boosty
Donate to support the project
GitHub account
GitHub profile