php method to convert content into images: 1. Extract the data required for dataurl storage through regular expressions, and then display it directly on the page; 2. Use the substr and strpos methods to save the image locally.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
How does php convert content into images? PHP convert dataurl into image image method
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 the substr and strpos methods
$imgdata = substr ( $imgstr , strpos ( $imgstr , "," ) + 1); $decodedData = base64_decode ( $imgdata ); file_put_contents ( '11.png' , $decodedData );
Recommended learning: "PHP Video tutorial》
The above is the detailed content of How to convert content into images in php. For more information, please follow other related articles on the PHP Chinese website!