ajax实现base64 图片上传示例 可压缩图片大小

35 篇文章 0 订阅
3 篇文章 0 订阅

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("压缩失败!");
			//调用上传方式  不压缩
		}
	}
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值