前端代码:
<input type="file" accept="image/*" onchange="monitorImg(this);">
function monitorImg(obj){
file = obj.files[0];
// 选择的文件是图片
if (file.type.indexOf("image") == 0) {
reader.readAsDataURL(file);
}
}
var reader = new FileReader(), img = new Image();
// 选择的文件对象
var file = null;
// 缩放图片需要的canvas
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
// base64地址图片加载完毕后
var image;//最终需要上传的图片
img.onload = function () {
console.log(1)
// 图片原始尺寸
var originWidth = this.width;
var originHeight = this.height;
// 最大尺寸限制
var maxWidth = 400, maxHeight = 400;
// 目标尺寸
var targetWidth = originWidth, targetHeight = originHeight;
// 图片尺寸超过400x400的限制
if (originWidth > maxWidth || originHeight > maxHeight) {
console.log(2)
if (originWidth / originHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
console.log(3)
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
console.log(4)
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
// canvas对图片进行缩放
canvas.width = targetWidth;
canvas.height = targetHeight;
// 清除画布
context.clearRect(0, 0, targetWidth, targetHeight);
// 图片压缩
context.drawImage(img, 0, 0, targetWidth, targetHeight);
image= canvas.toDataURL();//最终需要上传的图片
};
// 文件base64化,以便获知图片原始尺寸
reader.onload = function(e) {
img.src = e.target.result;
console.log(e.target)
};
php后端接收并保存:
public function add(){
$imgurl = $this -> input ->post('image');
$this->base64_image_content($imgurl,'保存的文件地址,空就是在根目录');
}
public function base64_image_content($base64_image_content,$path){
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
$type = $result[2];
$new_file = $path."/".date('Ymd',time())."/";
if(!file_exists($new_file)){
//检查是否有该文件夹,如果没有就创建,并给予最高权限
mkdir($new_file, 0700);
}
var_dump($result);
$new_file = $new_file.time().".{$type}";
var_dump($new_file);
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
var_dump($new_file);
return '/'.$new_file;
}else{
return false;
}
}
}