How PHP and Ajax work together on pictures (code)

Source: Internet
Author: User
This article introduces to you about the characteristics of PHP trait and usage introduction (with code), there is a certain reference value, the need for friends can refer to, I hope to help you.

1, processing save Base64 encoded picture, and return to save the picture URL (can be used to save the canvas to change the picture)
2, processing pictures, and return base64 encoded pictures (generally solve the problem of JS cross-domain)

Demo Code (test Server environment: localhost):

<! Doctype>

filesave.php Code:

<?phpfunction Rndstr () {$string = ' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ';    $len = rand (0,3) +5;    $rst = ";    $strl = strlen ($string);        for ($i =0; $i < $len; $i + +) {$ind = rand (0, $strl);        $s = $string [$ind];    $rst. = $s; } return $rst;} The type to be processed $type = $_post[' datatype '];//the picture to be processed (normal URL picture/base64 encoded picture) $GETIMG = $_post[' dataimg '];//1, processing save Base64 encoded picture, and returns the saved picture URL (which can be used to handle saving canvas-turned pictures) if ($type = = ' Get_imgurl ') {//with the current time + random string Set not duplicate file name $name = times (). Rndstr (); $img = str _replace (', ' + ', $getImg); $img = Base64_decode ($img);//Store picture, note whether the folder has Write permission $dir = Iconv ("UTF-8", "GBK", "upfile"); File_exists ($dir)) {mkdir ($dir, 0777,true);} $f = fopen (' upfile/'. $name. '. jpg ', ' w+ '); fwrite ($f, $img); fclose ($f);//output saved picture Urlecho ' upfile/'. $name. '. jpg ';//2, process the picture, and return Base64 encoded picture (generally solve the problem of JS cross-domain)}else if ($type = = ' Get_base64 ') {$pic = $GETIMG;//$arr = getimagesize ($pic) ;//$pic = "data:{$arr [' MIME ']};base64,". Base64_encode (file_get_contents ($pic)); $pic = "Data:image/jpg;base64,". Base64_encode (file_get_contents ($pic)); echo $pic;}? >

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.