Home > front end >  Is it possible to convert base64 image format?
Is it possible to convert base64 image format?

Time:10-07

Issue description:

I'm currently working on Ionic 6 / Capacitor / Angular 12 application. I'm using the giving @capacitor/camera plugin Who return me some base64 images (with getPhoto​ function).

If the user take directly photo from the device the function would return me JPEG base64 image.

But if user take photo from the library, I can get any other format as image (png, gif ...) and that cause issue in my case.

Because my backend want work only with JPEG files.

I already checked:

  • png-to-jpeg — package seem old/deprecated, I wasn't find any solution with it, and have npm medium and critical issue (so I ll skip it).
  • jimp — package seem to be what I need but cannot find any thread or example matching my problem.

Questions:

  • Did anyone know if it possible to convert image png to jpeg from base64 ?
  • If 'yes' — can it possible in Javascript and how ?
  • Else — Do you have any alternative alternative ?

CodePudding user response:

You can do it by changing the media type in the base64 string. The base64 string consists of the following:

data:[<mediatype>][;base64],<data>

So if you could change

data:image/png...

to

data:image/jpeg...

it should work fine. Whenever you will be creating a image to download, it will choose the bits in accordance with the lossless compression to generate a jpeg for you

CodePudding user response:

You may try sharp like below

const sharp = require("sharp");

async function convert() {
  try {
    await sharp("myfile.png")
      .toFormat("jpeg", { mozjpeg: true })
      .toFile("smyfile.jpeg");
  } catch (error) {
    console.log(error);
  }
}
  • Related