How to process images using php and ajax together (code)
This article introduces to you the characteristics and usage of Trait in PHP (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Process and save the base64-encoded image and return the saved image URL (can be used to process and save the image converted by CANVAS)
2. Process the image and return the base64-encoded image (generally solved JS cross-domain issues)
demo code (please use the server environment for testing: localhost):
<!DOCTYPE> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> </head> <body> <div>1、处理保存 base64编码 的图片,并返回保存的图片URL</div> <img id="get_imgUrl" src="" /> <div>2、处理图片,并返回 base64编码 的图片</div> <img id="get_base64" src="" /> <script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascript"> //1、处理保存 base64编码 的图片,并返回保存的图片URL function getNewImgUrl(){ // var new_img_src = mycanvas.toDataURL("image/jpg"); var new_img_src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAMAAAC7IEhfAAAAzFBMVEUAAAD///////////////////////////////////////////////////////////////////////////////////////////////////////////////////8slq////8fkKoolK4qla7q9fcikasVi6fs9vhkssVgsMMlk60bjqliscTp9Pfe7/P7/f6Fw9GXy9jV6u/R6e5Np7vv9/m53OWr1eBYrcA4nLRJpLr1+vzj8vVut8nF4ukKhaKAwM9er8L3+/3W6/B/v8+BkGs6AAAAHnRSTlMAA2QdWCLjy/bu68iSe3heH/h1CucH8s6fnZuajswXGpFAAAACYElEQVQ4y42V2XriMAyFnQBlX1qg+0QOsUNMkgIJFChQaOf932nkLDN2CP1Gd5gfS+dYEkSLYaX/0h41GqP2S78yJNei0m+DEu1+pRSr9ZoA8OaE31H0HTpvANDs1S656g0AhOv5ZitmM7HdzNchHtxUi9ydxBYx51RMLGsiKOfxQqJ3Gma84tF7zClCeUwoj9/x+NVQuA4WN7epVQhqz7HUjqHm/Zh+IlcMQQ8fSvZqA7nD0bOLnM2YJBuZohrqnX8eIfBE4b5ztGB0jtpTl7qow6ZegCRTxbBzAEsmbFTUTd6jCfuYWsIPwPHo3/TJTx0sh8Z7aMo3MgEWXCbyXXD9mZ1xs+SjLIYvAExCxm3Y7xLBzHfAnSKZc47PEpN2e2gbpAKw5pPU4WlGIjdFbkrTc74GqJA+Ws2z8vOvJzS5PH8njrb3yTMEm9xqvGiFAhhDHausCAy6CeCZ1CHcCksnPUflLLENoU5asFTcs5OkUge1FUeX0CK3EHFLtdlzAVzNeotHcHsBUgSl80Xw/1MXxbipGNfXxfwiT2X2yGt1e56IWWr41JWkYrhJBtef0FeecECMerEp1CLypqgbRObW2kyTlbYZZk4bN9xR5BwItMaVB0njhti4P46CL0fBFvkokNoI4FQ6XN4Sh+u3HK5/4+ofjuefx1VGD2Dlly0Amx5WAD1tpXydxAVJxelLWylk3EmXlIZmS6ozJmr0krW345yla49xvkvWXu/6ImVIX1+k6FL3Xq7mIFxG0TIM5Gq+79ZISRgDsw5K1M2BQa7EcGA+PrQAWg+P5kD/+/gDFJSp26C1IkoAAAAASUVORK5CYII='; dataImg = new_img_src.substring(22); $.ajax({ type:'post', url:'filesave.php', data:{dataimg:dataImg,datatype:'get_imgUrl'}, beforeSend:function(){ },success:function(str){ $('#get_imgUrl').attr('src', str); } }); } getNewImgUrl(); ////////////////////////////////////////////////////////////////////// //2、处理图片,并返回 base64编码 的图片 getBase64Img('http://qr.topscan.com/api.php?&w=100&m=10&fg=E60012&bg=E3CFB3&text=' + encodeURIComponent('https://blog.csdn.net/') , function(data){ // base64img = new Image(); // base64img.src = data; $('#get_base64').attr('src', data); }); function getBase64Img (sourceImgUrl , callback){ // var sourceImgUrl = 'http://qr.topscan.com/api.php?&w=200&m=0&fg=E60012&bg=E3CFB3&text=' + encodeURIComponent('https://blog.csdn.net/'); $.ajax({ type:'post', url:'filesave.php', data:{dataimg:sourceImgUrl,datatype:'get_base64'}, beforeSend:function(){ },success:function(str){ callback(str); } }); } </script> </body> </html>
filesave.php code:
<?php function 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; } //要处理的类型 $type = $_POST['datatype']; //要处理的图片(正常url图片 / base64编码图片) $getImg = $_POST['dataimg']; //1、处理保存 base64编码 的图片,并返回保存的图片URL(可用来处理保存CANVAS转成的图片的) if($type == 'get_imgUrl'){ //以当前时间+随机字符串设置的不会重复的文件名 $name = time() . rndStr(); $img = str_replace(' ', '+', $getImg); $img = base64_decode($img); //存储图片,注意文件夹是否有写入权限 $dir = iconv("UTF-8", "GBK", "upfile"); if (!file_exists($dir)){ mkdir ($dir,0777,true); } $f = fopen('upfile/' . $name . '.jpg', 'w+'); fwrite($f, $img); fclose($f); //输出保存的图片URL echo 'upfile/' . $name . '.jpg'; //2、处理图片,并返回 base64编码 的图片(一般解决JS跨域的问题) }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; } ?>
Recommended related articles:
Naming rules for php variables and usage of php variables (with code)
php implements each operation file Summary of methods (with code)
The above is the detailed content of How to process images using php and ajax together (code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
