If your web application supports user-uploaded images, you probably need to transform them to fit the design specification of your app.
JavaScript Image Manipulation Program (Jimp) allows you to easily manipulate and transform your images into any required format, style, or dimension. It also optimizes images for minimal file size, ensures high visual quality for an improved user experience, and reduces bandwidth.
With Jimp, you can resize and crop images, convert them to the image format that fits your needs, and apply filters and effects. In this tutorial, we’ll go over how the library works and describe some common use cases for Jimp image manipulation.
npm install --save jimp
Jimp can only be used on a limited range of image formats. Before you start working with the library, you’ll want to make sure it supports the formats you plan to include in your app.
Supported types include:
@jimp/jpeg
@jimp/png
@jimp/bmp
@jimp/tiff
@jimp/gif
Jimp offers both callback- and Promise-based APIs for manipulating images. For the purpose of this post, we’ll use Jimp’s Promise API.
​​The static Jimp.read
​ method accepts an image as an input. The input could be the location of an image file in the file system, a web address (URL), dimension (width and height), Jimp instance, or buffer. Then, it returns a Promise.
Jimp.read('http://www.example.com/path/to/lenna.jpg') .then(image => { // Do stuff with the image. }) .catch(err => { // Handle an exception. });
Jimp’s resize()
method alters the height and/or width of an image via a two-pass bilinear algorithm.
Syntax:
resize( w, h[, mode] )
Example:
const Jimp = require('jimp'); async function resize() { // Read the image. const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg'); // Resize the image to width 150 and heigth 150. await image.resize(150, 150); // Save and overwrite the image await image.writeAsync(`test/${Date.now()}_150x150.png`); } resize();
Original image:
Resized image:
Jimp.AUTO
can be passed as the value for the height or width and the image will be resized accordingly while maintaining aspect ratio. You cannot pass Jimp.AUTO
as the value for both height and width.
If no resizing algorithm is passed, Jimp uses Jimp.RESIZE_BILINEAR
as the default resizing algorithm. Other resizing algorithms that Jimp allows include:
Jimp.RESIZE_NEAREST_NEIGHBOR;
Jimp.RESIZE_BILINEAR;
Jimp.RESIZE_BICUBIC;
Jimp.RESIZE_HERMITE;
Jimp.RESIZE_BEZIER;
The crop()
function is used to crop an image to specified x
and y
coordinates and dimensions.
Syntax:
crop( x, y, w, h)
Example:
async function crop() { // Read the image. const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg'); await image.crop(500, 500, 150, 150); // Save and overwrite the image await image.writeAsync(`test/${Date.now()}_crop_150x150.png`); } crop()
Cropped image:
The rotate()
method rotates an image clockwise by a given number of degrees. The dimensions of the image remain the same.
Syntax:
rotate( deg[, mode] );
Example:
async function rotate() { // Read the image. const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg'); await image.rotate(45); // Save and overwrite the image await image.writeAsync(`test/${Date.now()}_rotate_150x150.png`); } rotate()
Output:
The flip()
method flips an image either horizontally or vertically. The default setting is to flip the image horizontally.
Syntax:
image.flip( horz, vert )
Example:
async function flip() { // Read the image. const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg'); await image.flip(true, false); // Save and overwrite the image await image.writeAsync(`test/${Date.now()}_flip_150x150.png`); console.log("flipped") } flip()
Output:
The opacity()
method multiplies the opacity of each pixel by a factor within the range of 0 and 1.
Syntax:
opacity( f );
Example:
async function opacity() { // Read the image. const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg'); await image.opacity(.5); // Save and overwrite the image await image.writeAsync(`test/${Date.now()}_opacity_150x150.png`); }
Output:
The greyscale modifier desaturates or removes color from an image and turns it to grayscale.
Syntax:
greyscale(); >
Example:
async function greyscale() { // Read the image. const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg'); await image.greyscale(); // Save and overwrite the image await image.writeAsync(`test/${Date.now()}_greyscale_150x150.png`); } greyscale()
Output:
The blur()
method blurs an image by r
pixels using a blur algorithm that produces an effect similar to a Gaussian blur, only much faster.
Syntax:
blur(r) // fast blur the image by r pixels
Example:
async function blur() { // Read the image. const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg'); await image.blur(20); // Save and overwrite the image await image.writeAsync(`test/${Date.now()}_blur_150x150.png`); } blur()
Output:
The composite()
method overlays an image over another Jimp image at x
, y
.
Syntax:
composite( src, x, y, [{ mode, opacitySource, opacityDest }] );
Example:
async function waterMark(waterMarkImage) { let watermark = await Jimp.read(waterMarkImage); watermark = watermark.resize(300,300); const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg'); watermark = await watermark image.composite(watermark, 0, 0, { mode: Jimp.BLEND_SOURCE_OVER, opacityDest: 1, opacitySource: 0.5 }) await image.writeAsync(`test/${Date.now()}_waterMark_150x150.png`); } waterMark('https://destatic.blob.core.windows.net/images/nodejs-logo.png');
Output:
​​You can write text on an image with the print()
API. Jimp supports only the Bitmap font format (.fnt). Fonts in other formats must be converted to .fnt to be compatible with Jimp.
Example:
async function textOverlay() { const font = await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK); const image = await Jimp.read(1000, 1000, 0x0000ffff); image.print(font, 10, 10, 'Hello World!'); } textOverlay();
Output:
We’ve only scratched the surface of use cases for Jimp. If you’re considering using Jimp as your primary image processor, check out the full documentation on the official GitHub and npm pages.
Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you’re interested in ensuring requests to the backend or third-party services are successful, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.
LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. Start monitoring for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowDesign React Native UIs that look great on any device by using adaptive layouts, responsive scaling, and platform-specific tools.
Angular’s two-way data binding has evolved with signals, offering improved performance, simpler syntax, and better type inference.
Fix sticky positioning issues in CSS, from missing offsets to overflow conflicts in flex, grid, and container height constraints.
From basic syntax and advanced techniques to practical applications and error handling, here’s how to use node-cron.
2 Replies to "Image processing with Node and Jimp"
hi how can i store the image to data base after resizing
Thanks. You helped me a lot