Home Backend Development PHP Tutorial How to process images using php and ajax together (code)

How to process images using php and ajax together (code)

Aug 03, 2018 am 11:48 AM
Process pictures

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 = &#39;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=&#39;;
    dataImg = new_img_src.substring(22);
    $.ajax({
            type:&#39;post&#39;,
            url:&#39;filesave.php&#39;,
            data:{dataimg:dataImg,datatype:&#39;get_imgUrl&#39;},
            beforeSend:function(){
            },success:function(str){
                $(&#39;#get_imgUrl&#39;).attr(&#39;src&#39;, str);
            }
    });
}
getNewImgUrl();
 
 
//////////////////////////////////////////////////////////////////////
 
 
//2、处理图片,并返回 base64编码 的图片
getBase64Img(&#39;http://qr.topscan.com/api.php?&w=100&m=10&fg=E60012&bg=E3CFB3&text=&#39; + encodeURIComponent(&#39;https://blog.csdn.net/&#39;) , function(data){
//    base64img = new Image();
//    base64img.src = data;
    $(&#39;#get_base64&#39;).attr(&#39;src&#39;, data);
});
function getBase64Img (sourceImgUrl , callback){
//    var sourceImgUrl = &#39;http://qr.topscan.com/api.php?&w=200&m=0&fg=E60012&bg=E3CFB3&text=&#39; + encodeURIComponent(&#39;https://blog.csdn.net/&#39;);
    $.ajax({
            type:&#39;post&#39;,
            url:&#39;filesave.php&#39;,
            data:{dataimg:sourceImgUrl,datatype:&#39;get_base64&#39;},
            beforeSend:function(){
            },success:function(str){
                callback(str);
            }
    });
}
</script>
 
 
 
 
</body>
</html>
Copy after login

filesave.php code:

<?php
function rndStr(){
    $string = &#39;0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;;
    $len = rand(0,3)+5;
    $rst = &#39;&#39;;
    $strl = strlen($string);
    for($i=0;$i<$len;$i++){
        $ind = rand(0, $strl);
        $s = $string[$ind];
        $rst .= $s;
    }
    return $rst;
}

//要处理的类型
$type = $_POST[&#39;datatype&#39;];
//要处理的图片(正常url图片 / base64编码图片)
$getImg = $_POST[&#39;dataimg&#39;];

//1、处理保存 base64编码 的图片,并返回保存的图片URL(可用来处理保存CANVAS转成的图片的)
if($type == &#39;get_imgUrl&#39;){
	//以当前时间+随机字符串设置的不会重复的文件名
	$name = time() . rndStr();
	
	$img = str_replace(&#39; &#39;, &#39;+&#39;, $getImg);
	$img = base64_decode($img);
	
	//存储图片,注意文件夹是否有写入权限
	$dir = iconv("UTF-8", "GBK", "upfile");
	if (!file_exists($dir)){
		mkdir ($dir,0777,true);
	}
	$f = fopen(&#39;upfile/&#39; . $name . &#39;.jpg&#39;, &#39;w+&#39;);
	fwrite($f, $img);
	fclose($f);
	//输出保存的图片URL
	echo &#39;upfile/&#39; . $name . &#39;.jpg&#39;;
	
//2、处理图片,并返回 base64编码 的图片(一般解决JS跨域的问题)
}else if($type == &#39;get_base64&#39;){
	$pic = $getImg;
	//$arr = getimagesize($pic);
	//$pic = "data:{$arr[&#39;mime&#39;]};base64," . base64_encode(file_get_contents($pic));
	$pic = "data:image/jpg;base64," . base64_encode(file_get_contents($pic));
	echo $pic;
}
?>
Copy after login

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

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.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

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? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

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 permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

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...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

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�...

See all articles