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 = '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>
Copy after login

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;
}
?>
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 Article Tags

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)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

11 Best PHP URL Shortener Scripts (Free and Premium)

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Introduction to the Instagram API

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Working with Flash Session Data in Laravel

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

Build a React App With a Laravel Back End: Part 2, React

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

12 Best PHP Chat Scripts on CodeCanyon

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

Notifications in Laravel

See all articles