js前端图片压缩处理
1.html代码
<input type="file" onchange="selectImg(this)" accept="image/*" name="file" >
<img id="showImg" src="" style="display: none;width: 80px; height: 80px;" alt="" width="100px" height="100px">
<button type="button" class="inf_button blue_g" onclick="javascript:save();">保存</button>
2.js代码
<script type="text/javascript">
//执行压缩图片
function compressImage(input) {
var file = input.files[0];
var options = {
quality: 0.6,
maxWidth: 800,
maxHeight: 800,
mimeType: 'image/jpeg',
success: function(result) {
var img = new Image();
img.src = URL.createObjectURL(result);
img.onload = function() {
URL.revokeObjectURL(this.src);
document.body.appendChild(img);
console.error(img);
};
},
error: function(err) {
alert('请上传图片');
console.log(err.message);
},
};
new Compressor(file, options);
}
function selectImg(file) {
if (!file.files || !file.files[0]) {
return;
}
//定以一个读取文件的对象
var reader = new FileReader();
console.log("图片原始大小:" + file.files[0].size / 1024 + "KB");
reader.onload = function (evt) {
//获取的是图片的base64代码
var replaceSrc = evt.target.result;
compressedImg(replaceSrc,function (base) {
document.getElementById("showImg").src = base;
console.log("压缩后:" + base.length / 1024 + "KB");
});
// 再将获取值赋给img标签
$("#showImg").attr("style","display:block;width: 80px; height: 80px;");
$('#showImg').attr("src", replaceSrc);
};
reader.readAsDataURL(file.files[0]);
}
//图片压缩代码
function compressedImg(path, callback) {
var img = new Image();
img.src = path;
img.onload = function () {
var that = this;
// 默认按比例压缩
var w = that.width,
h = that.height;
var quality = 0.2; // 默认图片质量为0.7
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 创建属性节点
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// quality值越小,所绘制出的图像越模糊
var base64 = canvas.toDataURL('image/jpeg', quality);
// 回调函数返回base64的值
callback(base64);
}
}
function save(){
var img = $("#showImg").attr("src");
if(!img && (!$('#hiddimg').val())){
alert('必须上传资格证书');
return;
}
$.ajax({
url: '/doeditinfo',
data:{img :img},
dataType:'json',
type:'post',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
success:function(data){
console.error(data);
if(data.code ==200){
alert('保存成功!');
}else {
alert('保存失败!');
}
},
error:function()
{},
timeout:2000,
async:true,
})
}
</script>