Home php教程 php手册 ajax图片上传剪切

ajax图片上传剪切

Jun 13, 2016 am 10:09 AM
ajax upload by cut area back picture supply Way at last user of choose

允许用户以AJAX的方式上传图片
·允许用户选择图片的一定区域
·最后,提供一个裁减后图片的下载地址

我们将要用到三个文件

·index.php - 包含图片上传表单以及剪切界面
·upload.php - 提供上传功能
·crop.php - 提供剪切功能

从技术角度看,流程如下所示:

1.用户上传文件(index.php)
2.index.php将上传的图片POST到upload.php以处理上传图片程序,返回JSON数据包括图片名,长和宽。
3.根据JSON里的数据和innerHTML,我们将图片放在页面上
4.初始化javascript剪切工具
5.生成下载连接(crop.php)

让我们来看看index.php

index.php是我们的主要文件,用户通过他来上传和下载图片。

我们需要YUI提供的以下几个组件:
·yahoo-dom-event.js - 操作和解析DOM
·dragdrop - 基于图片剪切工具
·element - 基于图片剪切工具
·resize - 基于图片剪切工具
·connection - 为AJAX请求, 此例通过AJAX上传
·json - 解析JSON
·imagecropper - 我们最重要的工具

当然我们要用到 Yahoo combo handling并且加上上面提到的脚本和样式表:[code] href="http://yui.yahooapis.com/2.5.2/build/resize/assets/skins/sam/resize.css"
/>
href="http://yui.yahooapis.com/2.5.2/build/imagecropper/assets/skins/sam/imagecropper.css"
/>

src="http://yui.yahooapis.com/combo?2.5.2/build/yahoo-dom-event/yahoo-dom-event.js&2.5.2/build/dragdrop/dragdrop-min.js&2.5.2/build/element/element-beta-min.js&2.5.2/build/resize/resize-beta-min.js&2.5.2/build/imagecropper/imagecropper-beta-min.js&2.
5.2/build/connection/connection-min.js&2.5.2/build/json/json-min.js">
[/code]然后用户一定会通过AJAX上传图片,所以我们在页面上加一个表单。[code]

enctype="multipart/form-data" method="post" name="uploadForm"
id="uploadForm">
        Image :



[/code]点击上传按钮来激活上传程序。[code]// add listeners
YAHOO.util.Event.on('uploadButton', 'click', uploader.carry);[/code]同样,我们也需要两个容器:
·imageContainer - 将包含我们上传的图片
·downloadLink - 将包含下载连接[code]


[/code]两个容器事后将通过innerHTML更新

AJAX上传
对于AJAX的上传,请参见Code Central上的教程

强烈推荐此教程,我下载了示例代码,根据自己的需要改动了一点点,最后我搞了一个非常不错的JSON对象[uploader],它只有一个方法 carry。后者只是提交表单数据到一个指定的URL。[code]uploader = {
        carry: function(){
                // set form
                YAHOO.util.Connect.setForm('uploadForm', true);
                // upload image
                YAHOO.util.Connect.asyncRequest('POST', 'upload.php', {
                        upload: function(o){
                                // parse our json data
                                var jsonData = YAHOO.lang.JSON.parse(o.responseText);

                                // put image in our image container

                            
YAHOO.util.Dom.get('imageContainer').innerHTML = 'ajax图片上传剪切 src="' + jsonData.image + '" width="' + jsonData.width + '" height="' +
jsonData.height + '" alt="" />';

                                // init our photoshop
                                photoshop.init(jsonData.image);

                                // get first cropped image
                                photoshop.getCroppedImage();
                        }
                });
        }
};
[/code]当上传完成,我们得到早前提到过的JSON数据。[code]{"image" : "images/myimage.jpg", "width" : "500", "height" : 400}
[/code]此数据和我们用来放置图片的容器imageContainer将以yuiImg作为id[code]YAHOO.util.Dom.get
('imageContainer').innerHTML = '';[/code]指定图片的长和宽是非常重要的,除非图片剪切工具工作不正常。
下面我们将实例化另一个JSON对象photoshop,我们一起来看看。

我们的photoshop对象[code]photoshop = {
        image: null,
        crop: null,

        init: function(image){
                // set our image
                photoshop.image = image;

                // our image cropper from the uploaded image
                photoshop.crop = new YAHOO.widget.ImageCropper('yuiImg');
                photoshop.crop.on('moveEvent', function() {
                        // get updated coordinates
                        photoshop.getCroppedImage();
                });
        },

        getCroppedImage: function(){
                var coordinates = photoshop.getCoordinates();

              var url = 'crop.php?image=' + photoshop.image +
'&cropStartX=' + coordinates.left +'&cropStartY=' +
coordinates.top +'&cropWidth=' + coordinates.width
+'&cropHeight=' + coordinates.height;
              
YAHOO.util.Dom.get('downloadLink').innerHTML = 'download cropped image';               

        },

        getCoordinates: function(){
                return photoshop.crop.getCropCoords();
        }
};
[/code]这个初始化方法初始化了yuiImg[code]photoshop.crop = new
YAHOO.widget.ImageCropper('yuiImg');[/code]我们同样要声明moveEvent方法,每当这个图片被移动或是被调整大小,我们就调用getCroppedImage这个方法来更新下载连接。[code]photoshop.crop.on
('moveEvent', function() {
        // get updated coordinates
        photoshop.getCroppedImage();
});
[/code]getCroppedImage方法将生成裁减后的图片地址。在PHP里实现,我们需要
·要处理的图片
·X,Y轴的坐标
·裁减后的图片长和宽

幸运的是,YUI的剪切工具里有一个方法满足了我们的需要,它就是getCropCoords()方法。所以,无论什么时候调用getCroppedImage方法,我们取到剪切图片的坐标,然后生成一个下载连接。[code]// get coordinates
var coordinates = photoshop.getCoordinates();

// build our url
var
url = 'crop.php?image=' + photoshop.image + '&cropStartX=' +
coordinates.left +'&cropStartY=' + coordinates.top
+'&cropWidth=' + coordinates.width +'&cropHeight=' +
coordinates.height;

// put download link in our page
YAHOO.util.Dom.get('downloadLink').innerHTML = 'download cropped image';
[/code]index.php的所有内容就在这里了。

upload.php[code]
          if ($ext == "jpg") {
                      // generate unique file name
                  $newName = 'images/'.time().'.'.$ext;

                  // upload files
                if ((move_uploaded_file($_FILES['uploadImage']['tmp_name'], $newName))) {

                        // get height and width for image uploaded
                        list($width, $height) = getimagesize($newName);

                        // return json data
                           echo '{"image" : "'.$newName.'", "height" : "'.$height.'", "width" : "'.$width.'" }';
                }
                else {
                           echo '{"error" : "An error occurred while moving the files"}';
                }
          }
          else {
                     echo '{"error" : "Invalid image format"}';
          }
}
[/code]upload.php就像它写的那样,只解析jpg格式的图片,然后生成一个唯一的文件名,置于images的文件夹内,最后生成DOM可操作的JSON数据。当然images文件夹要设置为可读写。

crop.php[code]// get variables
$imgfile = $_GET['image'];
$cropStartX = $_GET['cropStartX'];
$cropStartY = $_GET['cropStartY'];
$cropW = $_GET['cropWidth'];
$cropH = $_GET['cropHeight'];

// Create two images
$origimg = imagecreatefromjpeg($imgfile);
$cropimg = imagecreatetruecolor($cropW,$cropH);

// Get the original size
list($width, $height) = getimagesize($imgfile);

// Crop
imagecopyresized($cropimg, $origimg, 0, 0, $cropStartX, $cropStartY, $width, $height, $width, $height);

// force download nes image
header("Content-type: image/jpeg");
header('Content-Disposition: attachment; filename="'.$imgfile.'"');
imagejpeg($cropimg);

// destroy the images
imagedestroy($cropimg);
imagedestroy($origimg);
[/code]我们可以通过crop.php剪切上传的图片。首先我们得到所有的通过AJAX传递给我们的变量。[code]// get variables
$imgfile = $_GET['image'];
$cropStartX = $_GET['cropStartX'];
$cropStartY = $_GET['cropStartY'];
$cropW = $_GET['cropWidth'];
$cropH = $_GET['cropHeight'];
[/code]我们创建两个图片,原始图片和剪切了的图片,通过imagecopyresized方法来生成剪切图片。我们加入两个头部信息,一个告诉游览器这是一个图片,另一个是保存图片的对话框。

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
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)

How to use Xiaohongshu account to find users? Can I find my mobile phone number? How to use Xiaohongshu account to find users? Can I find my mobile phone number? Mar 22, 2024 am 08:40 AM

With the rapid development of social media, Xiaohongshu has become one of the most popular social platforms. Users can create a Xiaohongshu account to show their personal identity and communicate and interact with other users. If you need to find a user’s Xiaohongshu number, you can follow these simple steps. 1. How to use Xiaohongshu account to find users? 1. Open the Xiaohongshu APP, click the "Discover" button in the lower right corner, and then select the "Notes" option. 2. In the note list, find the note posted by the user you want to find. Click to enter the note details page. 3. On the note details page, click the "Follow" button below the user's avatar to enter the user's personal homepage. 4. In the upper right corner of the user's personal homepage, click the three-dot button and select "Personal Information"

How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? Mar 22, 2024 am 08:06 AM

With the continuous development of social media, Xiaohongshu has become a platform for more and more young people to share their lives and discover beautiful things. Many users are troubled by auto-save issues when posting images. So, how to solve this problem? 1. How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? 1. Clear the cache First, we can try to clear the cache data of Xiaohongshu. The steps are as follows: (1) Open Xiaohongshu and click the "My" button in the lower right corner; (2) On the personal center page, find "Settings" and click it; (3) Scroll down and find the "Clear Cache" option. Click OK. After clearing the cache, re-enter Xiaohongshu and try to post pictures to see if the automatic saving problem is solved. 2. Update the Xiaohongshu version to ensure that your Xiaohongshu

Log in to Ubuntu as superuser Log in to Ubuntu as superuser Mar 20, 2024 am 10:55 AM

In Ubuntu systems, the root user is usually disabled. To activate the root user, you can use the passwd command to set a password and then use the su- command to log in as root. The root user is a user with unrestricted system administrative rights. He has permissions to access and modify files, user management, software installation and removal, and system configuration changes. There are obvious differences between the root user and ordinary users. The root user has the highest authority and broader control rights in the system. The root user can execute important system commands and edit system files, which ordinary users cannot do. In this guide, I'll explore the Ubuntu root user, how to log in as root, and how it differs from a normal user. Notice

How to post pictures in TikTok comments? Where is the entrance to the pictures in the comment area? How to post pictures in TikTok comments? Where is the entrance to the pictures in the comment area? Mar 21, 2024 pm 09:12 PM

With the popularity of Douyin short videos, user interactions in the comment area have become more colorful. Some users wish to share images in comments to better express their opinions or emotions. So, how to post pictures in TikTok comments? This article will answer this question in detail and provide you with some related tips and precautions. 1. How to post pictures in Douyin comments? 1. Open Douyin: First, you need to open Douyin APP and log in to your account. 2. Find the comment area: When browsing or posting a short video, find the place where you want to comment and click the "Comment" button. 3. Enter your comment content: Enter your comment content in the comment area. 4. Choose to send a picture: In the interface for entering comment content, you will see a "picture" button or a "+" button, click

How to set lock screen wallpaper on wallpaper engine? How to use wallpaper engine How to set lock screen wallpaper on wallpaper engine? How to use wallpaper engine Mar 13, 2024 pm 08:07 PM

WallpaperEngine is a software commonly used to set desktop wallpapers. Users can search for their favorite pictures in WallpaperEngine to generate desktop wallpapers. It also supports adding pictures from the computer to WallpaperEngine to set them as computer wallpapers. Let’s take a look at how wallpaperengine sets the lock screen wallpaper. Wallpaperengine setting lock screen wallpaper tutorial 1. First enter the software, then select installed, and click "Configure Wallpaper Options". 2. After selecting the wallpaper in separate settings, you need to click OK on the lower right. 3. Then click on the settings and preview above. 4. Next

Can wallpaper engine be shared among families? Can wallpaper engine be shared among families? Mar 18, 2024 pm 07:28 PM

Does Wallpaper support family sharing? Unfortunately, it cannot be supported. Still, we have solutions. For example, you can purchase with a small account or download the software and wallpapers from a large account first, and then change to the small account. Simply launching the software is perfectly fine. Can wallpaperengine be family shared? Answer: Wallpaper does not currently support the family sharing function. 1. It is understood that WallpaperEngine does not seem to be suitable for family sharing environments. 2. In order to solve this problem, it is recommended that you consider purchasing a new account; 3. Or download the required software and wallpapers in the main account first, and then switch to other accounts. 4. Just open the software with a light click and it will be fine. 5. You can view the properties on the above web page"

How to make ppt pictures appear one by one How to make ppt pictures appear one by one Mar 25, 2024 pm 04:00 PM

In PowerPoint, it is a common technique to display pictures one by one, which can be achieved by setting animation effects. This guide details the steps to implement this technique, including basic setup, image insertion, adding animation, and adjusting animation order and timing. Additionally, advanced settings and adjustments are provided, such as using triggers, adjusting animation speed and order, and previewing animation effects. By following these steps and tips, users can easily set up pictures to appear one after another in PowerPoint, thereby enhancing the visual impact of the presentation and grabbing the attention of the audience.

How to arrange two pictures side by side in wps document How to arrange two pictures side by side in wps document Mar 20, 2024 pm 04:00 PM

When using WPS office software, we found that not only one form is used, tables and pictures can be added to the text, pictures can also be added to the table, etc. These are all used together to make the content of the entire document look richer. , if you need to insert two pictures into the document and they need to be arranged side by side. Our next course can solve this problem: how to place two pictures side by side in a wps document. 1. First, you need to open the WPS software and find the picture you want to adjust. Left-click the picture and a menu bar will pop up, select "Page Layout". 2. Select "Tight wrapping" in text wrapping. 3. After all the pictures you need are confirmed to be set to "Tight text wrapping", you can drag the pictures to the appropriate position and click on the first picture.

See all articles