Home > Back-end >  How to render SVG and convert to PNG in react native
How to render SVG and convert to PNG in react native

Time:12-11

In my application, avatars are available for users to select, they will be generated randomly using the api of DiceBear, I searched in several forums and websites on the internet and I didn't find a way to:

1 - show this svg list that I generated with DiceBear's api; (Edit: This can be solved very easily using the react-native-svg library, the problem now is converting to PNG to send to the server!)

2 - How can I convert the selected svg into png to send to my app's server, which has an api all in PHP, and php doesn't have SVG support to do this conversion on the backend, I believe it has to be done on the front and sent in png!

Anyone have any idea how I can solve this problem? From in PHP, or with React Native to convert this svg?

Important information: I use EXPO and typescript; API in PHP;

CodePudding user response:

You can draw the SVG image on a <canvas> and then get the data URL from the <canvas>. Here I draw the SVG three times: First as SVG, then in the canvas and the last is an <img> with the PNG data. You can then use the PNG data URL for your POST request to the server.

Note that you don't need to display all the images. You can just hide the canvas and leave out the <img>.

document.addEventListener('DOMContentLoaded', e => {
  let svg01 = document.getElementById('svg01');
  let canvas = document.getElementById('canvas');
  let ctx = canvas.getContext('2d');
  
  let img01 = document.getElementById('img01');
  
  let img = new Image();
  
  img.addEventListener('load', e => {
    canvas.width = e.target.width;
    canvas.height = e.target.height;
    ctx.drawImage(e.target, 0, 0);
    img01.src = canvas.toDataURL('image/png');
    console.log('The Data URL that goes into the request:', canvas.toDataURL('image/png'));
  });
  img.src = `data:image/svg xml,${svg01.outerHTML}`;
});
<div>
  <svg id="svg01" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="30" height="30">
    <circle r="4" cx="4" cy="4" fill="red" />
    <rect x="4" y="4" width="6" height="6" fill="navy"/>
  </svg>
</div>
<canvas id="canvas"></canvas>
<div>
<img id="img01"/>
</div>

CodePudding user response:

If you want to do it the PHP way, someone in SO has already done it with Imagick here

  • Related