Skip to content
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

Not able to compress image; Buffer.from(base64string, 'base64') #373

Open
dudeful opened this issue Dec 18, 2020 · 0 comments
Open

Not able to compress image; Buffer.from(base64string, 'base64') #373

dudeful opened this issue Dec 18, 2020 · 0 comments

Comments

@dudeful
Copy link

dudeful commented Dec 18, 2020

I get the input from the user as a base64 string, and then on my server, I convert it using Buffer.from(base64string, "base64").

The issue is that the output from imagemin is not compressed at all. I'm logging the size of the data before and after the process. Although it works perfectly when I pass binary data (such as from fs.readFile...), it seems not to be possible to use binary data that has been converted from base64 strings.

Any thoughts on this?

my code:

const imagemin = require("imagemin");
const imageminJpegtran = require("imagemin-jpegtran");
const imageminMozjpeg = require("imagemin-mozjpeg");
const imageminPngquant = require("imagemin-pngquant");
const fs = require("fs");

const myPic = () => {
  return new Promise((resolve, reject) => {
    fs.readFile("/image.txt", (err, data) => {
      if (err) throw err;
      resolve(Buffer.from(data, "base64"));
    });
  });
};

const logMyPic = async () => {
  const picBuff = await myPic();
  return picBuff;
};

logMyPic().then((res) => {
  console.log("Original File Size: " + Math.round(res.length / 1024));

  const compressImg = async (img) => {
    const files = await imagemin.buffer(img, {
      plugins: [
        imageminJpegtran(),
        imageminMozjpeg({
          quality: [10],
        }),
        imageminPngquant({ quality: [0.1, 0.12] }),
      ],
    });
    return files;
  };
  compressImg(res).then((data) => {
    console.log("Compressed File Size: " + Math.round(res.length / 1024));
    fs.writeFile("/image2.txt", data, (err, data) => {
      if (err) throw err;
    });
  });
});

note that here in this code I'm reading a base64 string from a .txt file for testing purposes only, the real scenario will happen on the server with the base64 string being provided by the user

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

1 participant