您的位置:首页 > 其它

swfupload+imgareaselect打造头像图片在线编辑无刷新上传

2014-10-25 08:50 627 查看
http://www.cnblogs.com/aluode/archive/2012/11/01/2749289.html

正在做一个项目,需要一个会员头像在线编辑并上传的功能,百度了下大多是基于flash去实现在线编辑的,而且上传完必须刷新下,于是我想到了imgareaselect

首先你得去下载Jquery文件1.4版本以上,imgareaselect插件,swfupload插件,百度下就知道哪里下了。

目录结构:



Demo程序包下载:IconUpload

1、imgareaselect.php



<?php
session_start();
$ssession_id = session_id();
$icon = './upload/icon.jpg';
$icon_min = './upload/icon_min.jpg';
include './imgareaselect.html';
?>




2、imgareaselect.html



<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="./js/jquery-1.4.2.min.js"></script>

<link rel="stylesheet" type="text/css" href="./imgareaselect/imgareaselect-default.css" />
<script type="text/javascript" src="./imgareaselect/jquery.imgareaselect.min.js"></script>

<link href="./swfupload/swfupload.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="./swfupload/swfupload.js"></script>
<script type="text/javascript" src="./swfupload/swfupload.queue.js"></script>
<script type="text/javascript" src="./swfupload/fileprogress.js"></script>
<script type="text/javascript" src="./swfupload/handlers.js"></script>
<script type="text/javascript">
<!--
var upload1;
window.onload = function() {
upload1 = new SWFUpload({
// Backend Settings
upload_url: "./icon_upload.php",
post_params: {"PHPSESSID" : "<?php echo $ssession_id;?>"},

// File Upload Settings
file_size_limit : "300",    // 300kb
file_types : "*.jpg;*.jpeg;*.png;*.gif",
file_types_description : "jpg,jpeg,png,gif",
file_upload_limit : "1",
file_queue_limit : "1",

// Event Handler Settings (all my handlers are in the Handler.js file)
file_dialog_start_handler : fileDialogStart,
file_queued_handler : fileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_start_handler : uploadStart,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,

// Button Settings
button_image_url : "./swfupload/XPButtonUploadText_61x22.png",
button_placeholder_id : "spanButtonPlaceholder1",
button_width: 61,
button_height: 22,

// Flash Settings
flash_url : "./swfupload/swfupload.swf",

custom_settings : {
progressTarget : "fsUploadProgress1",
cancelButtonId : "btnCancel1"
},

// Debug Settings
debug: false
});
$('#icon').imgAreaSelect({
x1: 100, y1: 100, x2: 200, y2: 200,
aspectRatio: '1:1',
handles: true,
fadeSpeed: 200,
onSelectChange: preview
});
}

function preview(img, selection) {
if (!selection.width || !selection.height)
return;

var scaleX = 100 / selection.width;
var scaleY = 100 / selection.height;
$('#preview img').css({
width: Math.round(scaleX * $('#icon').width()),
height: Math.round(scaleY * $('#icon').height()),
marginLeft: -Math.round(scaleX * selection.x1),
marginTop: -Math.round(scaleY * selection.y1)
});

$('#x1').val(selection.x1);
$('#y1').val(selection.y1);
$('#x2').val(selection.x2);
$('#y2').val(selection.y2);
$('#w').val(selection.width);
$('#h').val(selection.height);
}

function save_img(){
var icon_min = $('#selectbanner').attr('src');
$.post("./imgareaselect_save.php",  {
'x':$('#x1').val(),
'y':$('#y1').val(),
'w':$('#w').val(),
'h':$('#h').val()
},
function(r){
//把裁剪后图片加载到原处
if(r == '1'){
alert('保存头像成功!');
var dateTime=new Date();
$('#selectbanner').attr('src',icon_min+'?'+dateTime.getMinutes()+dateTime.getSeconds());
}
}
);
}
//-->
</script>
<div align="center">
<table align="center">
<tr>
<td>
<div><img id="icon" src="<?php echo $icon;?>" style="width: 400px; "/></div>
</td>
<td>
<div id="preview" style="width: 100px; height: 100px; overflow: hidden;">
<img id="icon_min" src="<?php echo $icon;?>" style="width: 100px; height: 100px;" />
</div>
</td>
</tr>
<tr>
<td colspan="2">
<br>
你当前的头像LOGO:
<br>
<div><img id="selectbanner" src="<?php echo $icon_min;?>"></div>
<br>
<form id="form1" action="index.php" method="post" enctype="multipart/form-data">
<div>
<div class="fieldset flash" id="fsUploadProgress1">
<span class="legend">头像上传</span>
</div>
<div style="padding-left: 5px;">
<span id="spanButtonPlaceholder1"></span>
<input type="button" value="开始上传" onclick="upload1.startUpload();" style="margin-left: 2px; font-size: 8pt; height: 22px;" />
<input id="btnCancel1" type="button" value="取消上传" onclick="cancelQueue(upload1);" disabled="disabled" style="margin-left: 2px; height: 22px; font-size: 8pt;" />
<span style="cursor:pointer" onclick="save_img()">[保存头像]</span>
<br />
</div>
</div>
</form>
</td>
</tr>
</table>

<table style="display:none">
<tr>
<td style="width: 10%;"><b>X<sub>1</sub>:</b></td>
<td style="width: 30%;"><input type="text" id="x1" value="100" /></td>
<td style="width: 20%;"><b>Width:</b></td>
<td><input type="text" value="100" id="w" /></td>
</tr>
<tr>
<td><b>Y<sub>1</sub>:</b></td>
<td><input type="text" id="y1" value="100" /></td>
<td><b>Height:</b></td>
<td><input type="text" id="h" value="100" /></td>
</tr>
<tr>
<td><b>X<sub>2</sub>:</b></td>
<td><input type="text" id="x2" value="200" /></td>
<td></td>
<td></td>
</tr>
<tr>
<td><b>Y<sub>2</sub>:</b></td>
<td><input type="text" id="y2" value="200" /></td>
<td></td>
<td></td>
</tr>
</table>

</div>




3、imgareaselect_save.php



<?php
sliceBanner();
function sliceBanner(){
$x = (int)$_POST['x'];
$y = (int)$_POST['y'];
$w = (int)$_POST['w'];
$h = (int)$_POST['h'];
$filename = trim($_POST['pic']);
if(isset($filename)){
$uploadBanner =  getFolder().'icon.jpg';
/*if(!file_exists($uploadBanner)){
$uploadBanner = './images/icon.jpg';
}*/
$sliceBanner =  getFolder().'icon_min.jpg';
$src_pic = getImageHander($uploadBanner);
if(!$src_pic){
echo '0';exit;
}
$dst_pic = imagecreatetruecolor(100, 100);
imagecopyresampled($dst_pic, $src_pic, 0, 0, $x, $y, 100, 100, $w, $h);
imagejpeg($dst_pic, $sliceBanner);
//chmod($sliceBanner, 0777);
imagedestroy($src_pic);
imagedestroy($dst_pic);
echo '1';exit;
}
echo '0' ;exit;
}
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;
}
function getFolder(){
global $user_id;
$pathStr = './upload/';
if ( strrchr( $pathStr , "/" ) != "/" ) {
$pathStr .= "/";
}
//$pathStr .= $user_id.'/';
if ( !file_exists( $pathStr ) ) {
if ( !mkdir( $pathStr , 0777 , true ) ) {
return false;
}
}
return $pathStr;
}
?>




4、icon_upload.php



<?php
// Code for Session Cookie workaround
if (isset($_POST["PHPSESSID"])) {
session_id($_POST["PHPSESSID"]);
} else if (isset($_GET["PHPSESSID"])) {
session_id($_GET["PHPSESSID"]);
}

// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
$POST_MAX_SIZE = ini_get('post_max_size');
$unit = strtoupper(substr($POST_MAX_SIZE, -1));
$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
header("HTTP/1.1 500 Internal Server Error"); // This will trigger an uploadError event in SWFUpload
echo "POST exceeded maximum allowed size.";
exit(0);
}

// Settings
$save_path = "./upload/";// The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
if ( !file_exists( $save_path ) ) {
if ( !mkdir( $save_path , 0777 , true ) ) {
HandleError("can not make dir");
exit(0);
}
}
$upload_name = "Filedata";
$max_file_size_in_bytes = 314400;                // 300k in bytes
$extension_whitelist = array("jpg", "jpeg", "png","gif");    // Allowed file extensions
$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';                // Characters allowed in the file name (in a Regular Expression format)

// Other variables
$MAX_FILENAME_LENGTH = 260;
$file_name = "";
$file_extension = "";
$uploadErrors = array(
0=>"There is no error, the file uploaded with success",
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder"
);

// Validate the upload
if (!isset($_FILES[$upload_name])) {
HandleError("No upload found in \$_FILES for " . $upload_name);
exit(0);
} else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
HandleError($uploadErrors[$_FILES[$upload_name]["error"]]);
exit(0);
} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
HandleError("Upload failed is_uploaded_file test.");
exit(0);
} else if (!isset($_FILES[$upload_name]['name'])) {
HandleError("File has no name.");
exit(0);
}

// Validate the file size (Warning: the largest files supported by this code is 2GB)
$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
if (!$file_size || $file_size > $max_file_size_in_bytes) {
HandleError("File exceeds the maximum allowed size");
exit(0);
}

if ($file_size <= 0) {
HandleError("File size outside allowed lower bound");
exit(0);
}

// Validate file extension
$path_info = pathinfo($_FILES[$upload_name]['name']);
$file_extension = $path_info["extension"];
$is_valid_extension = false;
foreach ($extension_whitelist as $extension) {
if (strcasecmp($file_extension, $extension) == 0) {
$is_valid_extension = true;
break;
}
}
if (!$is_valid_extension) {
HandleError("Invalid file extension");
exit(0);
}
// Validate file name (for our purposes we'll just remove invalid characters)
//$file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name']));
$file_name = 'base_icon.'.$file_extension;
if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH) {
HandleError("Invalid file name");
exit(0);
}

list($width, $height) = getimagesize($_FILES[$upload_name]["tmp_name"]);
$percent = round($width/400,1);
if($percent > '1'){
$new_width = 400;
$new_height = $height / $percent;
}else{
$new_width = $width;
$new_height = $height;
}

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = getImageHander($_FILES[$upload_name]["tmp_name"]);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_p,$save_path.'icon.jpg');
imagedestroy($image);
imagedestroy($image_p);

if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
HandleError("File could not be saved.");
exit(0);
}
exit(0);

function getImageHander ($url) {
$size=@getimagesize($url);
switch($size['mime']){
case 'image/jpg': $im = imagecreatefromjpeg($url);break;
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;
}
/* Handles the error output. This error message will be sent to the uploadSuccess event handler.  The event handler
will have to check for any error messages and react as needed. */
function HandleError($message) {
echo $message;
}
?>




5、swfupload/handlers.js 修改 uploadSuccess函数,在里面追加上传完成后的动作



function uploadSuccess(file, serverData) {
try {
var progress = new FileProgress(file, this.customSettings.progressTarget);
progress.setComplete();
progress.setStatus("上传完成");
progress.toggleCancel(false);
//window.top.location.reload(); //刷新重载页面
//无刷新更新图片
var icon = document.getElementById('icon').getAttribute("src");
var dateTime=new Date();
document.getElementById('icon').setAttribute("src",icon+'?'+dateTime.getMinutes()+dateTime.getSeconds());
document.getElementById('icon_min').setAttribute("src",icon+'?'+dateTime.getMinutes()+dateTime.getSeconds());
} catch (ex) {
this.debug(ex);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: