1

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;

Will Lopes
  • 222
  • 1
  • 7

2 Answers2

2

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>
chrwahl
  • 8,675
  • 2
  • 20
  • 30
1

The DiceBear API supports the PNG format since a few days.

https://github.com/dicebear/dicebear/discussions/179

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 12 '21 at 10:45