index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>测试</title>
<!-- <link rel="stylesheet" href="./css/index.css" /> -->
<!-- <link rel="stylesheet" href="./css/index_1.css" /> -->
<script type="text/javascript" src="script/ys.js"></script>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<div class="free-upload">
<p>
上传您的照片,上传图片
</p>
<div class="free-upload-photo">
<span id="photo_img"></span>
<input type="file" id="photo" onchange="start_upload(this)"/>
</div>
</div>
<img src="" id="csimg" width="200" height="200"/>
</body>
<script>
function start_upload(obj){
if(!isCanvasSupported){
console.log("2222");
}else{
compress(event, function(base64Img){
$("#csimg").attr("src",base64Img);
console.log(base64Img);
// 把base64转成图片 ajax提交后台处理
$.ajax({
type: "post",
dataType: "json",
scriptCharset: "utf-8",
url: "touxiang.php",
data: {img : base64Img},
success: function(data){
if (data.res == 1) {
// 成功提示!
alert(data.msg);
}else{
// 失败提示!
alert(data.msg);
}
},
error:function(argument) {
alert(" 错误信息:" + XMLResponse.responseText); }
})
});
}
}
</script>
</html>
touxiang.php 示例;
<?php
/**
* base64图片上传
* @param $base64_img
* @return array
*/
$base64_img = trim($_POST['img']);
//存放在当前目录的upload文件夹下
$up_dir = './upload/';
if(!file_exists($up_dir)){
mkdir($up_dir,0777);
}
if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
$type = $result[2]; // 图片类型
if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
// 新的地址 加 文件名
$new_file = $up_dir.date('YmdHis_').'.'.$type;
// 解码base64 写入文件
if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
$img_path = str_replace('../../..', '', $new_file);
/* 存储新照片 删除老照片 */
// 没有数据库操作 此处省略
// 上传成功
die(json_encode(array('res'=>1,'msg'=>'上传成功!') ) );
// echo '图片上传成功</br>![](' .$img_path. ')';
}else{
// 上传失败
die(json_encode(array('res'=>0,'msg'=>'上传失败!') ) );
}
}else{
//文件类型错误
die(json_encode(array('res'=>0,'msg'=>'图片上传类型错误!') ) );
}
}else{
//文件错误
die(json_encode(array('res'=>0,'msg'=>'文件错误!') ) );
}
ys.js 压缩核心文件
//判断是否存在画布
function isCanvasSupported() {
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
//压缩方法
function compress(event, callback) {
if ( typeof (FileReader) === 'undefined') {
console.log("当前浏览器内核不支持base64图标压缩");
//调用上传方式 不压缩
} else {
try {
var file = event.currentTarget.files[0];
if(!/image\/\w+/.test(file.type)){
alert("请确保文件为图像类型");
return false;
}
var reader = new FileReader();
reader.onload = function (e) {
var image = $('<img/>');
image.load(function () {
console.log("开始压缩");
var square = 700; // 定义变量
var canvas = document.createElement('canvas');
canvas.width = square; // 新图片的width
canvas.height = square;// 新图片的height
var context = canvas.getContext('2d'); // 画布绘图环境
context.clearRect(0, 0, square, square);
var imageWidth;
var imageHeight;
var offsetX = 0;
var offsetY = 0;
if (this.width > this.height) {
imageWidth = Math.round(square * this.width / this.height);
imageHeight = square;
offsetX = - Math.round((imageWidth - square) / 2);
} else {
imageHeight = Math.round(square * this.height / this.width);
imageWidth = square;
offsetY = - Math.round((imageHeight - square) / 2);
}
context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight);
var data = canvas.toDataURL('image/jpeg');
//压缩完成执行回调
callback(data);
});
image.attr('src', e.target.result);
};
reader.readAsDataURL(file);
} catch(e) {
console.log("压缩失败!");
//调用上传方式 不压缩
}
}
}