PHP turns Dataurl into image image method to summarize _php skills

Source: Internet
Author: User
Tags base64

PHP turns Dataurl into image Image method

Using canvas generated pictures, is using Dataurl, PHP can not directly save the File_put_contents method to the local computer, need to do a bit of transcoding.

Picture Dataurl as follows

$imgstr = ' data:image/png;base64,ivborw0kggoaaaansuheugaaaauaaaafcayaaacnbyblaaaaheleqvqi12p4//8/ w38giaxdibke0dhxgljnbaao9txl0y4ohwaaaabjru5erkjggg== ';

Method One:

By just extracting the data needed for dataurl storage, and then showing 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 Two:

If you just want to save the picture to the local, you can use the substr and Strpos methods

 
$imgdata = substr ($imgstr, Strpos ($imgstr, ",") + 1);
$decodedData = Base64_decode ($imgdata);
File_put_contents (' 11.png ', $decodedData);

Thank you for reading, I hope to help you, thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.