Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 2, 2024 07:54 am GMT

WebP Image Optimisation BlurHash with Sharp in NodeJS

In this blog post, we'll cover how to convert images into WebP format and create blur hash images to store in your database to show as placeholders. WebP is used to create images that only need to be used in applications.
Resizing to Fit WebP
First, there's an important thing to note when using WebP. There is a maximum width and height of 16383 (according to Google, the creators of WebP - documented here).
If you forget to implement this you'll get a sharp error saying:

Processed image is too large for the WebP format

So we need to implement code to resize this if necessary before converting:

This code just does a quick check to see if it needs to be resized and returns the sharp instance if needed.
Notice that width and height are optional on the metadata. I haven't seen these values returned as undefined, but in the event an image is corrupted ensure to handle the errors.
Converting To WebP
Next, we convert the image to WebP. We'll make use of the function above to resize if needed.

This returns our converted image to WebP.
For more configuration read more about using Sharp here
Creating the BlurHash
We also want to create a BlurHash to store in our database for showing a placeholder while the image loads over the network.

This returns us the 36-character hashed string that can be used with BlurHash on the front end.
In our react front end we can use it like this:

Convert to fit your use case, but that's all you need to show blurred placeholders before your already optimised WebP image loads on the front end.
Read more about BlurHash usage here
Thanks for reading

Original Link:

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To