Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
shenxxu720 opened this issue Dec 9, 2023 · 1 comment

Comments

@shenxxu720
Copy link

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
Copy link

PabloPerezDeCiriza commented Dec 11, 2023

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();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants