SoFunction
Updated on 2025-03-10

Summary of the method of converting dataurl into image image

PHP converts dataurl to image image method

The images generated using canvas are dataurl. PHP cannot be saved directly to the local computer through the file_put_contents method, so it needs to be transcoding.

The picture dataurl is as follows

$imgstr = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';

Method 1:

The data required to store the data by regular extraction, and then display it directly on the page

if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
  die("error");
}
 
$content = base64_decode($matches[2]);
header('Content-Type: '.$matches[1]);
header('Content-Length: '.strlen($content));
 
echo $content;
die;

 Method 2:

If you just want to save the image locally, you can use the substr and strpos methods

 
$imgdata = substr($imgstr,strpos($imgstr,",") + 1);
$decodedData = base64_decode($imgdata);
file_put_contents('',$decodedData );

Thank you for reading, I hope it can help you. Thank you for your support for this site!