Base64压缩
作者:互联网
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" session="false" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ include file="/WEB-INF/admin/views/watermark.jsp" %>
<%@ include file="/WEB-INF/admin/views/common/includeHeader.jsp" %>
<title>图片压缩</title>
</head>
<body>
<input id="file" type="file" capture="microphone" accept="image/*">
</body>
<script type="text/javascript">
$("#file").change(function(){
var m_this = this;
cutImageBase64(m_this,null,400,0.8);
})
function cutImageBase64(m_this,id,wid,quality) {
var file = m_this.files[0];
var URL = window.URL || window.webkitURL;
var blob = URL.createObjectURL(file);
var base64;
var quality=0.8;
var img = new Image();
img.src = blob;
img.onload = function() {
var that = this;
//生成比例
var w = that.width,
h = that.height,
scale = w / h;
w = wid || w;
h = w / scale;
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
$(canvas).attr({
width: w,
height: h
});
ctx.drawImage(that, 0, 0, w, h);
var size=file.size/1024;
// 如想确保图片压缩到自己想要的尺寸,如要求在50-150kb之间,请加以下语句,quality初始值根据情况自定
while (size > 64) {
quality -= 0.1;
size=canvas.toDataURL('image/jpeg', quality);
}
// 防止最后一次压缩低于最低尺寸,只要quality递减合理,无需考虑
while (size < 12) {
quality += 0.1;
size=canvas.toDataURL('image/jpeg', quality);
}
// 生成base64
base64 = canvas.toDataURL('image/jpeg', quality);
console.log(base64)
console.log(base64.length/1024)
console.log(file.size/1024)
};
}
</script>
</html>
标签:canvas,base64,压缩,Base64,file,var,quality,size 来源: https://www.cnblogs.com/whtjyt/p/16317668.html