tinify / tinify-nodejs

Node.js client for the Tinify API.
https://tinypng.com/developers
MIT License
414 stars 74 forks source link

How do I get the details of the compressed image before and after compression? #45

Open shenxxu720 opened 6 months ago

shenxxu720 commented 6 months ago

How do I get the details of the compressed image before and after compression? For example, the size of the picture before and after compression, picture compression ratio, etc

PabloPerezDeCiriza commented 6 months ago

Hi shenxxu720,

Thanks for reaching out!

There is not a built in functionality for this, but you can do it the next way:

const tinify = require("tinify");
const fs = require('fs');
const util = require('util');

tinify.key = "xxxxxxxxxxxxxxxx";
const source = tinify.fromFile("panda.png");
const stat = util.promisify(fs.stat);

async function compressImageAndLogSizes() {
    try {
        // Compress the image
        await source.toFile("optimized.png");

        // Get file sizes
        const sizeSource = (await stat("panda.png")).size;
        const sizeOutput = (await stat("optimized.png")).size;

        // Log size information
        console.log(`Source size is ${sizeSource}, optimized size is ${sizeOutput}`);
        console.log(`Compression ratio is ${1 - (sizeOutput / sizeSource)}`);
    } catch (error) {
        console.error("An error occurred:", error);
    }
}

compressImageAndLogSizes();