您当前的位置: 首页 > 学无止境 > JS经典实例 网站首页JS经典实例
javascript前端图片压缩并返回base64数据
发布时间:2017-02-12 21:06:01编辑:雪饮阅读()
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script>
function getinfo(obj){
filePath=window.URL.createObjectURL(obj.files[0]);
var img=document.createElement("img");
//由于图片没有设置宽高,浏览器渲染图片时宽高属性便没有,那么获取的宽高都将是0
//所以要在图片载入时(浏览器渲染前)就先获取其尺寸
img.onload=function(){
var canvas = document.createElement('canvas');
canvas.width=100;
canvas.height=100;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height,0,0,100,100);
//返回压缩后base64数据
var base64 = canvas.toDataURL('image/jpeg');
document.getElementById("aa").innerHTML="";
document.getElementById("aa").appendChild(canvas);
fanhui(base64);
};
img.src=filePath;
}
function fanhui(obj){ console.log(obj); }
</script>
</head>
<body>
<div id="aa">压缩后的图片将生成于这里</div>
<form method="post" action="index.php">
<input type="file" accept="image/*" name="aa" onchange="getinfo(this);"/>
</form>
</body>
</html>
关键字词:javascript,base64,图片压缩