search
Homephp教程PHP开发PHP summary of converting dataurl into image image method

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

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!