search
Homephp教程php手册ajax图片上传剪切
ajax图片上传剪切Jun 13, 2016 am 10:09 AM
ajaxuploadbycutareabackpicturesupplyWayat lastuserofchoose

允许用户以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
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
Scrapy基于Ajax异步加载实现方法Scrapy基于Ajax异步加载实现方法Jun 22, 2023 pm 11:09 PM

Scrapy是一个开源的Python爬虫框架,它可以快速高效地从网站上获取数据。然而,很多网站采用了Ajax异步加载技术,使得Scrapy无法直接获取数据。本文将介绍基于Ajax异步加载的Scrapy实现方法。一、Ajax异步加载原理Ajax异步加载:在传统的页面加载方式中,浏览器发送请求到服务器后,必须等待服务器返回响应并将页面全部加载完毕才能进行下一步操

如何使用CakePHP中的AJAX?如何使用CakePHP中的AJAX?Jun 04, 2023 pm 08:01 PM

作为一种基于MVC模式的PHP框架,CakePHP已成为许多Web开发人员的首选。它的结构简单,易于扩展,而其中的AJAX技术更是让开发变得更加高效。在本文中,将介绍如何使用CakePHP中的AJAX。什么是AJAX?在介绍如何在CakePHP中使用AJAX之前,我们先来了解一下什么是AJAX。AJAX是“异步JavaScript和XML”的缩写,是指一种在

jquery ajax报错403怎么办jquery ajax报错403怎么办Nov 30, 2022 am 10:09 AM

jquery ajax报错403是因为前端和服务器的域名不同而触发了防盗链机制,其解决办法:1、打开相应的代码文件;2、通过“public CorsFilter corsFilter() {...}”方法设置允许的域即可。

ajax传递中文乱码怎么办ajax传递中文乱码怎么办Nov 15, 2023 am 10:42 AM

ajax传递中文乱码的解决办法:1、设置统一的编码方式;2、服务器端编码;3、客户端解码;4、设置HTTP响应头;5、使用JSON格式。详细介绍:1、设置统一的编码方式,确保服务器端和客户端使用相同的编码方式,通常情况下,UTF-8是一种常用的编码方式,因为它可以支持多种语言和字符集;2、服务器端编码,在服务器端,确保将中文数据以正确的编码方式进行编码,再传递给客户端等等。

Nginx中404页面怎么配置及AJAX请求返回404页面Nginx中404页面怎么配置及AJAX请求返回404页面May 26, 2023 pm 09:47 PM

404页面基础配置404错误是www网站访问容易出现的错误。最常见的出错提示:404notfound。404错误页的设置对网站seo有很大的影响,而设置不当,比如直接转跳主页等,会被搜索引擎降权拔毛。404页面的目的应该是告诉用户:你所请求的页面是不存在的,同时引导用户浏览网站其他页面而不是关掉窗口离去。搜索引擎通过http状态码来识别网页的状态。当搜索引擎获得了一个错误链接时,网站应该返回404状态码,告诉搜索引擎放弃对该链接的索引。而如果返回200或302状态码,搜索引擎就会为该链接建立索引

什么是ajax重构什么是ajax重构Jul 01, 2022 pm 05:12 PM

ajax重构指的是在不改变软件现有功能的基础上,通过调整程序代码改善软件的质量、性能,使其程序的设计模式和架构更合理,提高软件的扩展性和维护性;Ajax的实现主要依赖于XMLHttpRequest对象,由于该对象的实例在处理事件完成后就会被销毁,所以在需要调用它的时候就要重新构建。

在Laravel中如何通过Ajax请求传递CSRF令牌?在Laravel中如何通过Ajax请求传递CSRF令牌?Sep 10, 2023 pm 03:09 PM

CSRF代表跨站请求伪造。CSRF是未经授权的用户冒充授权执行的恶意活动。Laravel通过为每个活动用户会话生成csrf令牌来保护此类恶意活动。令牌存储在用户的会话中。如果会话发生变化,它总是会重新生成,因此每个会话都会验证令牌,以确保授权用户正在执行任何任务。以下是访问csrf_token的示例。生成csrf令牌您可以通过两种方式获取令牌。通过使用$request→session()→token()直接使用csrf_token()方法示例<?phpnamespaceApp\Http\C

使用HTML5文件上传与AJAX和jQuery使用HTML5文件上传与AJAX和jQuerySep 13, 2023 am 10:09 AM

当提交表单时,捕获提交过程并尝试运行以下代码片段来上传文件-//File1varmyFile=document.getElementById(&#39;fileBox&#39;).files[0];varreader=newFileReader();reader.readAsText(file,&#39;UTF-8&#39;);reader.onload=myFunc;functionmyFunc(event){&nbsp;&nbsp;varres

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),