BenYsil
BenYsil

Reputation: 147

NodeJS : Rotate a base64 image and save it

I want to make a function to rotate at 90° an base64 image. I tried to use Image and Canvas but it returns Error.

Here is the Code :

exports.Test64 = (req, res, next) => {
 console.log("TEST UPS")
  upsres.find().then(
    (ups) => {
      console.log('YES');
      console.log(ups[0].b64Image); // it works but after i don't think
      var image = new Image();
      var canvas = document.getElementById("c");
      var ctx = canvas.getContext("2d");
      image.src = ups[0].b64Image;
      canvas.width = image.height;
      canvas.height = image.width;
      ctx.rotate(-90 * Math.PI / 180);
      ctx.translate(-canvas.heigt,0);
      ctx.drawImage(image, 0, 0);
      dataURL= canvas.toDataURL();
      console.log(dataURL);
      res.status(200).json(dataURL);
      );
    }
  ).catch(
    (error) => {
      res.status(400).json({
        error:'Not Working'
      });
    }
  );
};

Someone have an answer why it doesn't work ? :)

Thanks to everyone

Upvotes: 0

Views: 5069

Answers (2)

BenYsil
BenYsil

Reputation: 147

exports.Testups = async (req, res, next) => {
  try {
    let ups = await upsres.find()
    const base64str = ups[0].b64Image;
    const buf = Buffer.from(base64str, 'base64');
    let image = await Jimp.read(buf);

    // rotate Function having a rotation as 90
    image.rotate(-90).getBase64(Jimp.MIME_PNG, function (err, src) {
    res.status(200).json(src);
    })
  }
  catch (e) { }
};

That's Working :)

Upvotes: 0

Mahesh Bhatnagar
Mahesh Bhatnagar

Reputation: 1080

We can use jimp libray to get rotate image. Please use following code

   var Jimp = require('jimp');
    const base64str ="R0lG"//
     const buf = Buffer.from(base64str, 'base64');
    const image = await Jimp.read(buf);

   // rotate Function having a rotation as 90
    image.rotate(90).getBase64(Jimp.MIME_JPEG, function (err, src) {
    console.log("rb is \n")
    console.log(src);
  })

Upvotes: 3

Related Questions