Do you ever encounter a situation where a user uploads one image and you have to change its resolution to show it in multiple places? We encountered it as well so we built the @knovator/image-resizer
package.
Images are available in different sizes and formats and need to be optimized to the required size to reduce the loading time. It also helps improve SEO, optimize performance, and incurs lower data costs.
Images often need to be resized or change it’s formats for the following purposes,
- Thumbnail
- Faster loading times
- Low resolution for previews
- The original high resolution for actual viewing
@knovator/image-resizer
automates the process of Image resizing so that developers don’t have to write code for it.
How does it work?
let’s assume that on the server there is one uploaded image and its URL is abc.com/images/user/profile.png
and it is in /public/images/user
folder.
- If the resizer package receives a request for this image with the same
resolution
andformat
, it doesn’t do anything and lets the server handle request normally. - If the package receives a request for an image with a different
resolution
orformat
, it generates an image in the following manner,- If image request is
abc.com/images/user/1000x850/profile.png
, then it generates image with1000x850
resolution on/public/images/user/1000x850
folder. - If image request is
abc.com/images/user/profile.webp
, then it generatesprofile
image inwebp
format at/public/images/user/
folder. - If the requested image already exists, it let it simply pass.
- If image request is
- Package only generates images on the specified folder, and leaves them on the server to serve it.
express.static
is good to serve generated images.
How to use it?
@knovator/image-resizer
is built as an express middleware, so NodeJS application with expressjs is good to start with.
Installation
npm i @knovator/image-resizer
# or
yarn add @knovator/image-resizer
Usage
- It only needs the input of a public folder path and you’re ready to go,
const { resize } = require('@knovator/image-resizer');
app.use(resize(__dirname + '/public'));
- It considers
jpg
,png
,webp
andjpeg
image formats. if you want to add other formats, you can configure it as well,
const { resize } = require('@knovator/image-resizer');
app.use(resize(__dirname + '/public', { extensions: ['.png', '.jpg', '.jpeg', '.webp'] }));
- Example usage in the
app.js
file with the express application
const express = require('express');
const app = express();
const PORT = 8080;
const { resize } = require('@knovator/image-resize');
app.get('/status', (_req, res) => {
res.send('All Okay');
});
app.use(resize(__dirname + '/public')); // important to use before express.static
app.use(express.static(__dirname + '/public'));
app.listen(PORT, () => {
console.log(`App started on ${PORT}`);
});
If you found it useful, don’t forget to star it on GitHub, and if you encounter any issue or want to add a feature, please let us know on Github-Issues.
Thank You