图片压缩上传,php接收并保存图片

前端代码:

<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;
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值