Convert Between JPEG & TIFF Files with NodeJS & Jimp
Introduction
Do you need to convert TIFF files to a JPEG format? Or a JPEG image to a TIFF format? This article will walk you through how to do that quickly and easily using Node.js and the Jimp npm package.
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 TIFF to JPEG
Let's convert a .tiff file to a .jpg format first. Make sure you have a .tiff file in the root of your project directory that you want to convert to a .jpg.
Here's the full code:
const Jimp = require("jimp")
 
Jimp.read("file.tiff", function (err, file) {
  if (err) {
    console.log(err)
  } else {
    file.write("new-image.jpg")
  }
})
Let's break down each part of the code:
  1. First, we import the jimp npm package and hold it in the Jimp variable.
  2. Then, we use the Jimp.read() function to process the image into something we can work with. We pass the path of the file.tiff file to the function. And the function returns a promise with an error (if it exists) and a file to work with.
  3. We do some error handling inside the callback function.
  4. Then, we write the new new-image.jpg file to the current directory with the file.write() function.
And you should see the new-image.jpg file is written to your directory.
Make sense? Cool! Let's move onto the next example in the next section.
Convert JPG to TIFF
Now let's convert a .jpg file to a .tiff format. Make sure you have a .jpg file in the root of your project directory that you want to convert to a .tiff.
Here's the full code:
const Jimp = require("jimp")
 
Jimp.read("image.jpg", function (err, file) {
  if (err) {
    console.log(err)
  } else {
    file.write("new-file.tiff")
  }
})
Here's the break down each part of the code:
  1. First, we import the jimp npm package and hold it in the Jimp variable.
  2. Then, we use the Jimp.read() function to process the image into something we can work with. We pass the path of the image.jpg file to the function. And the function returns a promise with an error (if it exists) and a file to work with.
  3. We do some error handling inside the callback function.
  4. Then, we write the new new-file.tiff file to the current directory with the image.write() function.
And you should see the new-file.tiff file written to your directory.
Conclusion
Now you know how to convert back and forth between .tiff and .jpg files using Node.js and Jimp!
Thanks for reading and let us know what you think in the comments!