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

不言
Release: 2023-04-03 14:46:01
Original
2691 people have browsed it

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!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!