Create / display image from dataURL

Is it possible to create and display an image file from dataURL received by POST? Sort of:

<? $imgstr = $_POST["imgdata"]; //data:image/png;base64,.... etc (it always PNG) echo base64_decode($imgstr); // idk what this really does ?> 

I cannot use the <img> tag to display it. It should act as a β€œnormal” image file.

+6
source share
3 answers

If, for example, your input

 // Red dot graphic, stolen from Wikipedia $imgstr = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='; 

Then you can do what you want with

 // Grab the MIME type and the data with a regex for convenience if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) { die("error"); } // Decode the data $content = base64_decode($matches[2]); // Output the correct HTTP headers (may add more if you require them) header('Content-Type: '.$matches[1]); header('Content-Length: '.strlen($content)); // Output the actual image data echo $content; die; 
+4
source

Yes, try:

 <img alt="Base64 Image" src="data:image/png;base64,{$imgstr}" /> 

Edit: Make sure you clear your $ _POST, so people don’t put in dangerous garbage ...

+6
source

You must set the correct header before echoing.

 header( 'Content-Type: image/jpeg' ); 
+1
source

Source: https://habr.com/ru/post/890961/


All Articles