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

PHP summary of converting dataurl into image image method

高洛峰
Release: 2016-12-27 09:42:07
Original
1155 people have browsed it

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;
Copy after login

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 );
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template