Home > php教程 > php手册 > Ajax PHP jQuery image screenshot upload

Ajax PHP jQuery image screenshot upload

WBOY
Release: 2016-07-11 20:00:43
Original
1263 people have browsed it

1. Functional analysis

Users upload pictures directly. After clicking the "Upload" button, they can preview the picture in the picture preview, and then preview the picture before cropping. When clicking the "Crop" button, confirm the cropping of the picture, and click "Crop" The result" area shows the cropped effect.

(Note: I save the uploaded files in the "/uploads" folder, and the screenshot results in the "/avatar" folder)

Preview the effect:


2. Solution

1. Plug-in selection

  • jQuery: This is a must-have plug-in and can be downloaded from the official website

http://docs.jquery.com/Downloading_jQuery

  • imgAreSselect: This is to implement image area selection on the client

http://odyniec.net/projects/imgareaselect/

  • uploadify: Implements the file upload function, supports multiple file uploads, and is very customizable.

http://www.uploadify.com/download/

The above plug-ins are used on the client. In fact, I also use some plug-ins when writing PHP in this program. In fact, the reason why I wrote "Image cropping and uploading" was because I read "PHP Rapid Development Toolbox" and wanted to practice it myself. The book has a website (http://www.pluginphp.com/), which contains the code of the entire book, and each plug-in has a corresponding demo, which is very good. The following are the PHP plug-ins used:

  • PIPHP_UploadFile.php: This is a php file with file upload function

http://www.pluginphp.com/plug-in11.php

  • PIPHP_ImageCrop.php: This php file has the function of cropping images.

http://www.pluginphp.com/plug-in15.php

2. Interaction diagram between client and server

For ease of understanding, I will put the interaction diagram here first. The green part is the main steps on the client side, and the pink part is the main steps on the server side. The interaction between the server and the client is completed through AJAX. It can be found that most operations are performed on the client side, and the communication between the server side and the client is just simple JSON data, so the user experience is very high.

Screenshot 1 Interaction diagram between client and server

3. Client files

What is displayed to the user is an html page. In order to learn and consolidate CSS knowledge, we built the following front-end page with DIV CSS, see screenshot 2.

Screenshot 2 Front page

The file related to the client is mainly an index.html, and other plug-in files will be referenced in this file, so it can be said that there is only one html file on the client side.

In addition, since the interaction between the client and the browser is mainly discussed here, the CSS aspect is skipped. Only the HTML code is listed here, starting with the part:

imgareaselect-default.css" />

layout.css" />

uploadify.css" type="text/css" rel="stylesheet" />

Cut and upload pictures

It can be seen that it mainly refers to some plug-in files. The above files (including CSS files and js files) can be downloaded from the link I gave, but the style sheet layout.css is a style sheet written by me. You can write it based on your own CSS knowledge.

The next step is the body part. The code may be a bit messy when viewed this way. It is recommended to use some tools with highlighting to view the code, such as DreamWeaver and other IDEs. If this is not possible, you can also use Firefox's "View Source" code" to see. (Firefox is not only a great browser, it’s also a great debugger!)

For the sake of convenience, I removed embellishments such as the "navigation bar" and footer copyright statement, and only gave the necessary html code.

 

 Picture upload

 


Upload pictures

 

 

 

Picture Preview

 

Crop result:

Crop preview:

div id="preview">

上面我用颜色区分开主要DIV区,这三块分别代表"上传图片区"、"大图展示区"、"截图结果区"与"选择预览区"。其中三个粗体部分是带有ID属性的空DIV,用来放图片用的。(到时时候动态加载图片到这些DIV中),因此这段代码形成的HTML框架如截图 2所示。(蓝色线条是block元素边界,此效果较是由火狐的插件制作而成):

截图 3 页面大体框架

基本的准备工作已经完成,待会儿再继续在这个框架上添加代码。咱们先介绍一下服务器上的PHP是怎么个情况。

 

4、服务器文件

服务器上主要用到两个PHP文件,一个用来处理上传图片的process.php,另外一个则是处理图片截图用的crop.php。不过,process.php文件包括插件PIPHP_UploadFile.php,而crop.php中包括PIPHP_ImageCrop.php插件。(这些插件的地址我在上面已经给出了)

=======

process.php主要接收上传图片,设置限制(比如文件的大小与格式),处理一些上传错误等,最后返回给客户端JSON,里面包含了所上传文件的一些信息(比如路径、大小等);当在客户端点击"上传"按钮的时候,会用异步(AJAX)的方式调用这个php文件。

=======

crop.php主要负责真正裁剪上传的图片,当在客户端返回裁剪的位置后(点击"裁剪"按钮后),以异步方式将数据以JSON的方式传递给服务器,crop.php真正裁剪图片后,将图片另存到网络的目录下,同时返回此图片的存储路径,然后再让客户端显示图片即可

 

三、用到的技术摘要

现在根据上面的交互图继续完善代码。因此我这节会交叉地完善html、js与php代码,并不会单独分开完善,这样在逻辑上会更好理解。

声明:新增的代码部分用粗体表示

 

1、uploadify上传

在html的head部分加入<script>标签,里面开始写主要的处理程序: </script>

<script><span style="font-family: 微软雅黑;"> </script>type="text/javascript"  src="/uploadify/jquery.uploadify.v2.1.4.min.js">

    

  $(document).ready(function(){

        //uploadify设置

            $('#pic_upload').uploadify({

                'uploader' : '/uploadify/uploadify.swf',

                'script' : 'process.php',        

                'cancelImg' : '/uploadify/cancel.png',

            });

  }

    

上面的代码只是uploadify这一个插件的配置项而已。为了增强用户体验可以详细配置其他选项,这参考这个插件的官方文档:http://www.uploadify.com/documentation/。上面的'script'选项就是选择服务器的处理脚本,我们这里就使用process.php了。上传文件到服务器后会让服务器自动调用这个程序。那么客户端怎么知道服务器的process.php调用完了呢?如何获取process.php反馈回来的信息呢?——其实uploadify它提供了一个"触发"选项onComplete,就是用来处理服务器的反馈信息的,我们稍后再写这个选项的内容,先看看process.php是返回哪些内容的呢。

2. Process.php feedback upload information

The task of process.php is to return JSON data to the browser (as for what JSON is, please refer to other tutorials. Just think of JSON as a "key/value" pair. It is very convenient for data transmission and reading. Pick). In PHP, the data is usually organized into an array first, and then json_encode() is used to convert the data into JSON. So what kind of data should process.php return to the browser?

  • Whether the file was uploaded successfully -> message
  • File upload status code    —> code
  • Storage path for file upload    —> path
  • Width of the image      —> width
  • Height of the picture      —> height
  • Scale ratio of the image      —> scale
  • The name of the picture     —> name

The reason why sets the scaling ratio of the image is because if the image size uploaded by the user is too large (such as 800x800), the DIV in the browser will be "stretched" and the layout will be disrupted. Therefore, we limit that when the browser displays the image, the length of any side cannot exceed 400px, otherwise it will be scaled in equal proportions when displayed. (For example, the 800x800 picture above will be displayed as 400x400, and the browser will also set the scale to 0.5).

In addition, this php file calls the PIPHP_UploadFile.php plug-in, which is used to "identify" and "move" the uploaded files.

The following is the process.php program:

require_once(dirname(__FILE__)."/../PIPHP_UploadFile.php");

$response=array(

'message'=>'Unknown upload error',

‘path’=>'',

'code'=>-4, //Upload the result code, 0 indicates success, -1 means failure

‘width’=>100,

‘height’=>100,

'scale'=>1, //Scale

'name'=>''

);

if (!empty($_FILES))

{

$name='picture';

$uploadFile='uploads/';

$maxLen=9*1024*1024;

$result=PIPHP_UploadFile($name,$uploadFile,$maxLen);

$response['code']=$result[0];

//Simple report on success

if($result[0]==0)

{

$response['message']='Upload successful! ';

        //$response['message']=$result[2];

        $response['path']=$result[1];

        $response['name']=$result[2];

        

        //获取图像的高度与宽度

        $fileName=iconv("utf-8","gb2312",$result[2]);

        list($width,$height)=getimagesize($_SERVER['DOCUMENT_ROOT'].$uploadFile.$fileName);

        $response['width']=$width;

        $response['height']=$height;

    }

    else

    {            

        switch($result[0])

        {

            case -1: $response['message']="上传失败"; break;

            case -2: $response['message']="文件类型错误";break;

            case -3: $response['message']="文件大小超过限制";break;

            default: $response['message']="错误代码:$result[0]";    

        }    

    }

}

else{

     $response['message']="上传文件出现错误!"."
";

}

    $json_str=json_encode($response);

    echo $json_str;

?>

其实这个程序因为有了if判断语句而显示有点大,其实逻辑还是挺简单的。无论如何,这个程序返回的我上面说的有关图片的上传信息(放在$json_str这变量里了)

 

3. Continue to improve the configuration of uplodify

As we know from the above, process.php returns a $json_str variable, which contains the path of the image, so that we can display the image in the browser! (Note that the image displayed at this time is already on the server)

Now add uploadify's 'onComplete' option, which tells the browser what to do when process.php returns data.

$('#pic_upload').uploadify({

'uploader' : '/uploadify/uploadify.swf',

'script' : 'process.php',

'cancelImg' : '/uploadify/cancel.png',

 'onComplete': function(event, ID, fileObj, response, data) {

json_str=JSON.parse(response);

var maxSize=400;

var width=json_str.width;

var height=json_str.height;

var scale=json_str.scale;

if(json_str.code == 0)

{

$('#uploadInfo').html(json_str.message '
Average upload speed: ' data.speed. toFixed(2) 'Kb/s');

                                   //Resize the image

      if(json_str.width > maxSize || json_str.height >maxSize){

if( json_str.width > json_str.height)

                                                                      

       width = maxSize;

Height = maxSize / json_str.width * json_str.height;

json_str.scale = maxSize / json_str.width;

     }

else

                                                                      

Height = maxSize;

width = maxSize / json_str.height * json_str.width;

json_str.scale = maxSize / json_str.height;

     }

                                                                                                  

      

$('#oriImage').html('');

Ajax PHP jQuery image screenshot upload       //

Insert preview image at the same time $('#preview').empty().html('').css({

Ajax PHP jQuery image screenshot upload overflow:'hidden',

width:'150px',

Height:'150px'

});

} else{

$('#uploadInfo').html('

Error code[' json_str.code ']:' json_str .message '

');

}

 

},

}); … 

The program here mainly does two things. First (the first color mark) displays the uploaded image. However, if the image is too large, it should display the scaled image and save the zoom ratio to in the scale variable; then (at the second color mark) initialize the cropping preview (using the jQuery method). Note that this is only initialization and does not dynamically display the cropping preview. The dynamic display part must be completed with the imgAreaSelection plug-in. Let’s start talking about this plug-in.

4. Use imgAreaSelection to get the screenshot point coordinates

Please go to the official website for instructions on how to use imgAreaSelection, and I won’t go into details here.

Since images are loaded dynamically, this plugin cannot be applied to images in advance. We can set a button. When the image is uploaded and displayed, we click the "Load Cropping Box" button to bind this plug-in to the image. So we first add a button to the html. I load the "Image Preview" DIV:

 

Picture Preview

Load crop frame

                                               

然后在head中的<script>标签中写点击事件处理程序:</script>

$(document).ready(function(){

        $('#pic_upload').uploadify({

                …

        });

        //加载裁剪框    

        $('#initCrop').click(function(e){

                ias=$('#oriImage img').imgAreaSelect({instance:true});

                ias.setOptions({ aspectRatio: '1:1', handle:true,

                                 hide:false,

                                 onSelectChange:preview2,

                                 onSelectEnd: function (img, selection) {

                                    json_str.x1=selection.x1;

                                    json_str.y1=selection.y1;

                                    json_str.cropWidth=selection.x2-selection.x1;

                                    json_str.cropHeight=selection.y2-selection.y1;

                                 },

                                });                    

        });

}

这里的onSelectChange选项就是当改变裁剪框时所要调用的函数,这里使用preview2函数名作为值,这个函数我是另外写在下面的,当然你也可以使用匿名函数的。我是为了强调这个函数,所以写成实名函数:

//图像预览函数

    function preview2(img, selection) {

        realWidth=json_str.width * json_str.scale;

        realHeight=json_str.height * json_str.scale;

        sizeWidth=150;sizeHeight=150;

        var scaleX = sizeWidth / selection.width ;

        var scaleY = sizeHeight / selection.height ;

    

        $('#preview img').css({

            width: Math.round(scaleX * realWidth) + 'px',

            height: Math.round(scaleY * realHeight) + 'px',

            marginLeft: - Math.round(scaleX * selection.x1) + 'px',

            marginTop: -Math.round(scaleY * selection.y1) + 'px'

        });

    };

这个函数的功能是实现动态显示截图区域图像的,这个区域大小是150x150像素的一个小框,这里它动态加载css,注意要跟上一节中的uploadify中onComplete中预加载此截图框要联系起来。那里它是这么设置的:

//同时插入预览图

             $('#preview').empty().html('Ajax PHP jQuery image screenshot upload').css({

                    overflow:'hidden',

                    width:'150px',

                    height:'150px'

             });                         

        }

Note that overflow:hidden means to hide images that exceed the 150x150 pixels in the image. In fact, this method is borrowed from : http://odyniec.net/projects/imgareaselect/examples-callback.html

In addition, the onSelectEnd option configuration in this plug-in: When the mouse leaves the drag box, the coordinates of the upper left corner of the cropping area and the length and width of the cropping area are stored in the json_str variable, and then transferred to crop .php function .

5. Send json_str data to crop.php

Use the ajax() method in jQuery to transfer the json_str variable to the server. First add a "crop" button in the html:

Crop" />

Here I used the

element. In fact, it is not necessary. It can be any element because we are using the powerful ajax() method of jQuery.

When the user determines that they want to crop, pressing this button will call the ajax() method. We write the handler in the <script> element in the head section: </script>

//Load the cropping frame

$('#initCrop').click(function(e){

 …

});

//Cut the action and pass the data to the server, while ajaxreturn the picture

$("#crop").click(function(e){

if(!(typeof json_str == 'undefined'))

                                                                                                                                                                                                   jsondata='data=' JSON.stringify(json_str);

$.ajax({

type: "POST",

<🎜>

data:jsondata,//$('#cropData').serialize(),

                                                                                         

                                                                                                                                                                                                         through

                                                                                                                                                                                            

                                                                                           

                             });

     }

else

                                                                      

alert('please load image first');

     }

                                                                                 

return false;               });

//Image preview function

function preview2(img, selection) {…};

The above code is waiting for crop.php to send the file path back. Once it is sent back, the function configured with the 'success' option will display the image in the DIV with the id of 'cropResult'.

6. crop.php truly crops uploaded images

The function of this crop.php file is also very simple. It uses the json_str variable returned by the browser. Since this variable contains the starting point coordinates and cropping height and width information required for screenshots, the PIPHP_ImageCrop.php plug-in is then called. The image is truly cropped. Then save the cropped image in another folder (I save the uploaded file in the uploads folder, and the screenshot results in the avatar folder), and return the path to the target folder to the browser for browsing The cropped image is displayed on the display.

Source code of this program:

require_once('../PIPHP_ImageCrop.php');

$json_str=json_decode($_POST['data']);

$x=$json_str->x1;

$y=$json_str->y1;

$scale=$json_str->scale;

$cropWidth=$json_str->cropWidth;

$cropHeight=$json_str->cropHeight;

$path=$json_str->path;

$filename=$json_str->name;

    $tofilename=iconv("utf-8","gb2312",$filename);

    

    $realX=$x/$scale;

    $realY=$y/$scale;

    $realWidth=$cropWidth/$scale;

    $realHeight=$cropHeight/$scale;

    

    $cropedImage=PIPHP_ImageCrop('http://'.$_SERVER['SERVER_NAME'].'/'.$path, $realX, $realY, $realWidth, $realHeight);

    

    $targetDir='avatar/';

    $targetFile=$targetDir.$tofilename;

    

    imagejpeg($cropedImage,$_SERVER['DOCUMENT_ROOT'].$targetFile);

    

    echo $targetDir.$filename.'?'.time();

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template