Menu

1 / 2

Tiny image placeholders with sharp: bytes for 8 to 32 px LQIPs

DEV Community: node·Sahadat Husain·11 days ago
#f950M0sg
#devtonodejs#devto#dev#bytes#webp
Reading 0:00
15s threshold

A blurred placeholder only needs to be 16 pixels wide, and as WebP it costs about 100 bytes. With sharp, a 16 × 11 WebP of a 1920 × 1280 photo came out at 108 bytes, or 167 characters as a data URI you can inline in your HTML. At 32 px it is 248 bytes. Format matters more than width at this size: the same 16 px placeholder is 330 bytes as JPEG and 600 bytes as PNG.

How do you make one?

Resize to a tiny width, encode, and base64 the buffer:

import sharp from ' sharp ' ;

const src = ' jpg-sample-photo-original.jpg ' ; console . log ( ' width format bytes base64 chars data URI chars ' ); for ( const w of [ 8 , 16 , 24 , 32 ]) { for ( const [ fmt , opts ] of [[ ' webp ' , { quality : 50 }], [ ' jpeg ' , { quality : 50 }], [ ' png ' , { compressionLevel : 9 }], [ ' avif ' , { quality : 50 }]]) { const buf = await sharp ( src ). resize ( w ). toFormat ( fmt , opts ). toBuffer (); const b64 = buf . toString ( ' base64 ' ); const uri = `data:image/ ${ fmt } ;base64, ${ b64 } ` ; console . log ( String ( w ).…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.