Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React js image to base64

Tags:

reactjs

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

like image 541
Illud Avatar asked Feb 20 '19 19:02

Illud


People also ask

How do I convert to Base64 in react native?

import RNFS from 'react-native-fs'; var data = await RNFS. readFile( "file://path-to-file", 'base64'). then(res => { return res }); This works fine.


1 Answers

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

like image 107
ramsesls Avatar answered Nov 15 '22 07:11

ramsesls