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

Ajax PHP jQuery image screenshot upload

Jul 11, 2016 pm 08:00 PM
ajax jquery php code picture Open source screenshot programming programming language software development

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();

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

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,

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

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.

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

See all articles