6

I want to convert an image to base64 from reactjs to save that image in mongo without uploading the image to the server and then converting it if not converting the image directly

Illud
  • 319
  • 1
  • 4
  • 12

1 Answers1

6

I share my solution

const getEmergencyFoundImg = urlImg => {
  var img = new Image();
  img.src = urlImg;
  img.crossOrigin = 'Anonymous';

  var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');

  canvas.height = img.naturalHeight;
  canvas.width = img.naturalWidth;
  ctx.drawImage(img, 0, 0);

  var b64 = canvas.toDataURL('image/png').replace(/^data:image.+;base64,/, '');
  return b64;
};

I recommend calling this function with async / await to build the object of the post.

The method extracts it from this source: https://base64.guru/developers/javascript/examples/convert-image

Ramsés López
  • 461
  • 7
  • 8