Ahmad Awais

NAVIGATE


SHARE


Resize & Optimize Images With JavaScript in Node.js

Ahmad AwaisAhmad Awais

Lately, I have been working with a couple of image-intensive projects with Node.js, Next.js, React.js, and really only with JavaScript. I used to use a package called gm to optimize and resize images but that came at a cost of installing a couple of other native packages like GraphicsMagick and ImageMagick for node.

Naturally, that’s not a good thing for a project that’s being used by several developers on macOS, Windows, Linux, and on Raspberry Pi in the near future. So, in search of a better and JavaScript the only good solution I finally found a package called Jimp โ€” which has been pretty great to work with. Props to Oliver Moran.

๐Ÿ”ฐ Resizing & Optimizing images in Node.js#

Let’s get started with Jimp and resize a set of images while also optimizing them in sort of an automated way. So, this is what you need:

โฏ Install Jimp#

At this point, I assume that you have Node.js/npm installed and you have already kickstarted a project using npm init. Am I right?!

npm install jimp

โฏ Read, Resize, Optimize, and Write#

Now that we have installed jimp, we need to use jimp to read an image path, resize it, optimize it, and finally write the new image to the same path.

/* RESIZE OPTIMIZE IMAGES */
const Jimp = require('jimp');

/**
 * Resize + optimize images.
 *
 * @param Array images An array of images paths.
 * @param Number width A number value of width e.g. 1920.
 * @param Number height Optional number value of height e.g. 1080.
 * @param Number quality Optional number value of quality of the image e.g. 90.
 */
module.exports = async (images, width, height = Jimp.AUTO, quality) => {
	await Promise.all(
		images.map(async imgPath => {
			const image = await Jimp.read(imgPath);
			await image.resize(width, height);
			await image.quality(quality);
			await image.writeAsync(imgPath);
		})
	);
};

Explanation#

  • await Jimp.read(imgPath) Reading the image.
  • await image.resize(width, height) Resize the image with the given width but I don’t use height so the default value of Jimp.AUTO would resize the height as per the given width but keeping the same aspect ratio. This keeps things easy, you don’t have to do the math.
  • await image.quality(quality) Set a certain quality like 90%.
  • await image.writeAsync(imgPath) Write the image without callback in an async way. Super important to not use the .write method with async/await. I’ve been down that rabbit hole.

That’s pretty much about it. Go ahead and use this function.

๐Ÿ“Ÿ Node.js Module: resize-optimize-images#

That’s right. I have wrapped this in a nice little yet configurable node module called resize-optimize-images that you can install in your Node.js projects. This is how you go about it.

โฏ Install#

npm install resize-optimize-images

โฏ Usage#

const resizeOptimizeImages = require('resize-optimize-images');

(async () => {
	// Set the options.
	const options = {
		images: ['path/to/image.jpg', 'path/to/image.png'],
		width: 1920,
		quality: 90
	};
	
	// Run the module.
	await resizeOptimizeImages(options);
})();

Have fun hacking with JavaScript in Node.js. Use your code for good. Peace!

๐ŸŒŸ Don’t forget to star this repository resize-optimize-images โ†’

Founder & CEO at Langbase.com ยท Ex VP DevRel Rapid ยท Google Developers Advisory Board (gDAB) founding member. ๐Ÿง‘โ€๐Ÿ’ป AI/ML/DevTools Angel Investor โฏ AI/ML Advisory Board member San Francisco, DevNetwork

๐ŸŽฉ Award-winning Open Source Engineer & Dev Advocate ๐ŸฆŠ Google Developers Expert Web DevRel ๐Ÿš€ NASA Mars Ingenuity Helicopter mission code contributor ๐Ÿ† 8th GitHub Stars Award recipient with 3x GitHub Stars Award (Listed as GitHub's #1 JavaScript trending developer).

๐ŸŒณ Node.js foundation Community Committee Outreach Lead, Member Linux Foundation, OpenAPI Business Governing Board, and DigitalOcean Navigator. ๐Ÿ“Ÿ Teaching thousands of developers Node.js CLI Automation (100 videos ยท 22 Projects) & VSCode.pro course. Over 142 Million views, 22 yrs Blogging, 56K developers learning, 200+ FOSS.

โœŒ๏ธ Author of various open-source dev-tools and software libraries utilized by millions of developers worldwide โ“ฆ WordPress Core Developer ๐Ÿ“ฃ TEDx Speaker with 100+ international talks.

โœจ As quoted by: Satya Nadella ยท CEO of Microsoft โ€” Awais is an awesome example for developers.
๐Ÿ™Œ Leading developers and publishing technical content for over a decade ๐Ÿ’œ Loves his wife (Maedah) โฏ Read more about Ahmad Awais.

๐Ÿ‘‹โ€ฆ Awais is mostly active on Twitter @MrAhmadAwais

๐Ÿ“จ

Developers Takeaway

Stay ahead in the web dev community with Ahmad's expert insights on open-source, developer relations, dev-tools, and side-hustles. Insider-email-only-content. Don't miss out - subscirbe for a dose of professional advice and a dash of humor. No spam, pinky-promise!

โœจ 172,438 Developers Already Subscribed
Comments 0
There are currently no comments.