概述
var ___theImgInfo = {
width: 0,
height: 0
}
//图片选择
$(document).on('click', '.the-img-view', function () {
$('#input-img').click();
});
//图片选中后预览
$(document).on('change', '#input-img', function () {
if ($(this).val().length <= 0) return;
//预览功能 start
var file = this.files[0];//获取file文件对象
var _imgDom = document.getElementById('the-img');
var reader = new FileReader();
reader.onload = function () {
_imgDom.src = this.result; //这里图片预览
$('#the-img').css('display', 'block');
$('#the-img-msg').css('display', 'none');
//获取图片原始宽高
_imgDom.onload = () => {
___theImgInfo.width = _imgDom.naturalWidth;
___theImgInfo.height = _imgDom.naturalHeight;
}
};
reader.readAsDataURL(file);
//预览功能 end
});
//图片压缩
function compress() {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = ___theImgInfo.width / 2;
canvas.height = ___theImgInfo.height / 2;
context.drawImage(document.getElementById('the-img'), 0, 0, ___theImgInfo.width / 2, ___theImgInfo.height / 2);
return canvas.toDataURL('image/jpeg', 0.5);// 压缩后质量
}
$(document).on('click', '#btn-submit', function () {
if ($('#the-img').attr('src').length <= 0) {
$.toast("请选择照片", "text");
return;
}
//上传图片并跳转
var _imgBase = compress();
});
最后
以上就是迅速小伙为你收集整理的js图片选择、预览、压缩的全部内容,希望文章能够帮你解决js图片选择、预览、压缩所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复