Convert Between PNG & BMP Files Using Node.js & Jimp
Do you need to convert BMP images to a PNG format? Or a PNG image to a BMP format? This article will walk you through how to do that quickly and easily using Node.js and the Jimp NPM package.
Jimp is an image processing library written in JavaScript with zero native dependencies. It allows you to do a ton of cool stuff with images in an easy manner.
Let's get started!
Table of Contents
Install Jimp NPM Package
First, you need to install the NPM package. You can install it with either the NPM or yarn command below:
NPM:
npm install jimp --save
Yarn:
yarn add jimp
Now we're ready to start writing some code and converting images!
Convert BMP to PNG
Let's convert a .bmp
file to a .png
format first. Make sure you have a .bmp
file in the root of your project directory that you want to convert to a .png
file.
Here's the full code:
const Jimp = require("jimp")
Jimp.read("image.bmp", function (err, image) {
if (err) {
console.log(err)
} else {
image.write("new-image.png")
}
})
Let's break down each part of the code:
- First, we import the
jimp
NPM package and hold it in theJimp
variable. - Then, we use the
Jimp.read()
function to process the image into something we can work with. We pass the path of theimage.bmp
file to the function. And the function returns a promise with anerror
(if it exists) and an image to work with. - We do some error handling inside the callback function.
- Then, we write the new
new-image.png
file to the current directory with theimage.write()
function.
Make sense? Cool! Let's move onto the next example in the next section.
Convert PNG to BMP
Now let's convert a .png
file to a .bmp
format. Make sure you have a .png
file in the root of your project directory that you want to convert to a .bmp
.
Here's the full code:
const Jimp = require("jimp")
Jimp.read("image.png", function (err, image) {
if (err) {
console.log(err)
} else {
image.write("new-image.bmp")
}
})
Here's the break down each part of the code:
- First, we import the
jimp
NPM package and hold it in theJimp
variable. - Then, we use the
Jimp.read()
function to process the image into something we can work with. We pass the path of theimage.png
file to the function. And the function returns a promise with anerror
(if it exists) and an image to work with. - We do some error handling inside the callback function.
- Then, we write the new
new-image.bmp
file to the current directory with theimage.write()
function.
And you should see the new BMP file in your directory after running the code.
Now you know how to convert back and forth between PNG and BMP files using Node.js and Jimp!