This is the 26th day of my participation in the August More Text Challenge

background

Projects often need to compress an image into the appropriate directory, mostly using the website tiny-PNG.

However, there is a problem here, that is, every time I have to repeatedly operate the file to move the picture from one directory to another, which is very inconvenient, so I came up with an idea, can I implement a small tool, a command to directly compress the picture and move to the specified directory?

So, there’s this project.

Here are the detailed implementation steps

Project preparation, Tinify library

While looking for the right image compression package, I found Tinify, an official image compression package from Tiny-PNG. This is uploading the image to the tiny-PNG server and then sending the compressed image back to us;

How to use Tinify

.1 const tinify = require("tinify");
2 tinify.key = "467Kbym9jl55NmS54HcK54Cr5wCP"; // This is false
3 tinify.fromBuffer().toBuffer()
...
Copy the code
  1. The first line is the introduction of a package, no problem;
  2. The second line is a key key given by Tiny-PNG. Since we are essentially using their service, we need to register on tiny-PNG’s official website and get a key
  3. The third line is the core code of a picture compression

1 discount ️ Click here to log in

2 discount ️ point a key is generated here

Implementation approach

  1. Read the file and read out all the PNG images.
  2. Compress the image through Tinify
  3. Writes the compressed image to the destination directory

So, as you can see from the three steps above, you need a source directory to read images, and then a destination directory to write images, which is done through the Minimist library.

To implement a command line tool with Node, you can refer to my previous article

conclusion

I’m not going to show you the code, but that’s the idea. The NPM package has been uploaded to nPMjs.com and is called compresse-pngs if you are interested