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

3

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.