How to convert content into images in php

藏色散人
Release: 2023-03-11 08:12:02
Original
3177 people have browsed it

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.

How to convert content into images in php

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

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 the substr and strpos methods

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

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!

Related labels:
php
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template