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

PHP summary of converting dataurl into image image method

Dec 27, 2016 am 09:42 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)