Home >Backend Development >PHP Tutorial > php+jquery+Jcrop实现下传-截取-保存图片功能

php+jquery+Jcrop实现下传-截取-保存图片功能

WBOY
WBOYOriginal
2016-06-13 12:55:22781browse

php+jquery+Jcrop实现上传-截取-保存图片功能

  现在很我网站都流行会员模块上传头像时添加在线截取图片功能,截取完之后再保存,最近也有很多网友问有没有这个功能啊,网站上有一款只实现前端截取图片功能的,至于保存的话就没实现,具体可以查看实现图片截取+预览功能的jquery插件(http://www.jq-school.com/Detail.aspx?id=45),现在分享用php+jquery+Jcrop实现上传-截取-保存图片功能的,文章后面可以打包下载,学习PHP的网友们可以参考哦。

 

前端代码如下:

$(document).ready(function(){
	var bar = $('.bar');
	var percent = $('.percent');
	var showimg = $('#showimg');
	var progress = $(".progress");
	var files = $(".files");
	var btn = $(".btn span");
	$("#fileupload").wrap("<form id='myupload' action='action.php' method='post' enctype='multipart/form-data'></form>");
	$("#fileupload").change(function(){  //选择文件
		$("#myupload").ajaxSubmit({
			dataType:  'json',	//数据&#26684;式为json 
			beforeSend: function() {	//开始上传 
				showimg.empty();	//清空显示的图片
				progress.show();	//显示进度条
				var percentVal = '0%';	//开始进度为0%
				bar.width(percentVal);	//进度条的宽度
				percent.html(percentVal);	//显示进度为0% 
				btn.html("上传中...");	//上传按钮显示上传中
			},
			uploadProgress: function(event, position, total, percentComplete) {
				var percentVal = percentComplete &#43; '%';	//获得进度
				bar.width(percentVal);	//上传进度条宽度变宽
				percent.html(percentVal);	//显示上传进度百分比
			},
			success: function(data) {	//成功
				//获得后台返回的json数据,显示文件名,大小,以及删除按钮
				files.html("<b>"&#43;data.name&#43;"("&#43;data.size&#43;"k)</b> <span class='delimg' rel='"&#43;data.pic&#43;"'>删除</span>");
				//显示上传后的图片
				var img = "upload/face/"&#43;data.pic;
				//判断上传图片的大小 然后设置图片的高与宽的固定宽
				if (data.width>240 && data.height<240){
					showimg.html("<img  src='"&#43;img&#43;"' id='cropbox'    style="max-width:90%" / alt=" php+jquery+Jcrop实现下传-截取-保存图片功能 " >");
				}else if(data.width<240 && data.height>240){
					showimg.html("<img  src='"&#43;img&#43;"' id='cropbox'    style="max-width:90%" / alt=" php+jquery+Jcrop实现下传-截取-保存图片功能 " >");
				}else if(data.width<240 && data.height<240){
					showimg.html("<img  src='"&#43;img&#43;"' id='cropbox'    style="max-width:90%"  style="max-width:90%" / alt=" php+jquery+Jcrop实现下传-截取-保存图片功能 " >");
				}else{
					showimg.html("<img  src='"&#43;img&#43;"' id='cropbox' / alt=" php+jquery+Jcrop实现下传-截取-保存图片功能 " >");
				}
				//传给php页面,进行保存的图片&#20540;
				$("#src").val(img);
				//截取图片的js
				$('#cropbox').Jcrop({
					aspectRatio: 1,
					onSelect: updateCoords,
					minSize:[240,240],
					maxSize:[240,240],
					allowSelect:false, //允许选择
					allowResize:false, //是否允许调整大小
					setSelect: [ 0, 0, 240, 240 ]
				});
				btn.html("上传图片");	//上传按钮还原
			},
			error:function(xhr){	//上传失败
				btn.html("上传失败");
				bar.width('0')
				files.html(xhr.responseText);	//返回失败信息
			}
		});
	});
	
	$(".delimg").live('click',function(){
		var pic = $(this).attr("rel");
		$.post("action.php?act=delimg",{imagename:pic},function(msg){
			if(msg==1){
				files.html("删除成功.");
				showimg.empty();	//清空图片
				progress.hide();	//隐藏进度条 
			}else{
				alert(msg);
			}
		});
	});
	
});

function updateCoords(c){
	$('#x').val(c.x);
	$('#y').val(c.y);
	$('#w').val(c.w);
	$('#h').val(c.h);
};

function checkCoords(){
	if (parseInt($('#w').val())) return true;
	alert('Please select a crop region then press submit.');
	return false;
};

 

php后台代码如下:

<?php
$action = $_GET['act'];
if($action=='delimg'){
	$filename = $_POST['imagename'];
	if(!empty($filename)){
		unlink('upload/face/'.$filename);
		echo '1';
	}else{
		echo '删除失败.';
	}
}else{
	$picname = $_FILES['mypic']['name'];
	$picsize = $_FILES['mypic']['size'];
	if ($picname != "") {
		if ($picsize > 1024000) {
			echo '图片大小不能超过1M';
			exit;
		}
		$type = strstr($picname, '.');
		if ($type != ".gif" && $type != ".jpg") {
			echo '图片&#26684;式不对!';
			exit;
		}
		$rand = rand(100, 999);
		$pics = date("YmdHis") . $rand . $type;
		//上传路径
		$pic_path = "upload/face/". $pics;
		move_uploaded_file($_FILES['mypic']['tmp_name'], $pic_path);
	}
	$size = round($picsize/1024,2);
	$image_size = getimagesize($pic_path);
	$arr = array(
		'name'=>$picname,
		'pic'=>$pics,
		'size'=>$size,
		'width'=>$image_size[0],
		'height'=>$image_size[1]
	);
	echo json_encode($arr);
}
?>

<?php
	if ($_SERVER['REQUEST_METHOD'] == 'POST'){
		//删除会员以前的头像
		if(file_exists($MemberFace)) {
			unlink($MemberFace);
		}
		$MemberFace = sliceBanner("cuteboy");
		echo $MemberFace;
		exit;
	}
	
	function sliceBanner($UserName){
		$x = (int)$_POST['x'];
		$y = (int)$_POST['y'];
		$w = (int)$_POST['w'];
		$h = (int)$_POST['h'];
		$pic = $_POST['src'];
		
		//剪切后小图片的名字
		$str = explode(".",$pic);//图片的&#26684;式
		$type = $str[1]; //图片的&#26684;式
		$filename = $UserName."_".date("YmdHis").".". $type; //重新生成图片的名字
		$uploadBanner = $pic;
		$sliceBanner = "upload/face/".$filename;//剪切后的图片存放的位置
		
		//创建图片
		$src_pic = getImageHander($uploadBanner);
		$dst_pic = imagecreatetruecolor($w, $h);
		imagecopyresampled($dst_pic,$src_pic,0,0,$x,$y,$w,$h,$w,$h);
		imagejpeg($dst_pic, $sliceBanner);
		imagedestroy($src_pic);
		imagedestroy($dst_pic);
		
		//删除已上传未裁切的图片
		if(file_exists($uploadBanner)) {
			unlink($uploadBanner);
		}
		//返回新图片的位置
		return $sliceBanner;
	}
	//初始化图片
	function getImageHander ($url) {
		$size=@getimagesize($url);
		switch($size['mime']){
			case 'image/jpeg': $im = imagecreatefromjpeg($url);break;
			case 'image/gif' : $im = imagecreatefromgif($url);break;
			case 'image/png' : $im = imagecreatefrompng($url);break;
			default: $im=false;break;
		}
		return $im;
	}
?>

 

打包下载

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