Welcome folks today in this tutorial we will be compressing
jpg and png images using tinypng
and tinyjpg
api in node.js. All the full source code of the application will be shown below
Get Started
In order to get started you need to go to official website of tinypng to get free api key
as shown here
And now after getting the api key
you need to create a new node.js
project in the empty directory and issue the below command
npm init -y
This will create the empty package.json
file for your project
And now you need to install the tinify
module of node.js as shown below
npm i tinify
After installing this library make an index.js
file and copy paste the following code into it
app.py
1 2 3 4 |
const tinify = require("tinify"); tinify.key = "YOUR_API_KEY"; tinify.fromFile("unoptimized.png").toFile("optimized.png"); |
As you can see we are importing the library at the very first
line of code and then we are setting the api_key
of your project simply copy paste it from your dashboard and then we are taking the input image
and compressing it
If you run your node.js
project by typing the below command
node index.js
As you can see it has compressed a 1.89MB
image to 368KB
optimized and compressed image as shown below
You can also compress jpg
images as well by node.js module
just change or modify the above snippet of code like this as shown below
1 2 3 4 |
const tinify = require("tinify"); tinify.key = "###yourapi###key"; tinify.fromFile("profile.jpg").toFile("optimized.jpg"); |