Home  >  Article  >  php教程  >  PHP summary of converting dataurl into image image method

PHP summary of converting dataurl into image image method

高洛峰
高洛峰Original
2016-12-27 09:42:071134browse

PHP method to convert dataurl into image image

The image generated using canvas uses dataurl. PHP cannot directly save it to the local computer through the file_put_contents method, so it needs to be transcoded.

The image dataurl is as follows

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

Method 1:

Extract the data required for dataurl storage through regular expressions, 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 substr and strpos method

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

Thank you for reading, I hope it can help everyone, thank you for your support of this site!

For more PHP summary of the method of converting dataurl into image image, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn