如何来通过JavaScript来进行图片本地压缩
作者: 张国军_Suger
开发工具与关键技术:HTML、JavaScript
有些时候我们需要一些HTML页面进行图片的本地压缩,下面直接上一下代码,希望可以帮到大家。
<!DOCTYPE html>
<html>
<head>
<title>通过JavaScript图片本地压缩</title>
</head>
<body>
<input type="file" id="file" />
<img src="" id="img" />
<script>
var oInput = document.getElementById('file')
var oImg = document.getElementById("img");
oInput.onchange = function () {
var fileData = oInput.files[0];
//base64Data:处理成功返回的图片base64
base64(fileData, function (base64Data) {
oImg.setAttribute("src", base64Data);
});
}
/**
* file:input上传图片
* backData:处理完成回调函数
*/
function base64(file, backData) {
var reader = new FileReader();
var image = new Image();
var canvas = createCanvas();
var ctx = canvas.getContext("2d");
// 文件加载完处理
reader.onload = function () {
var result = this.result;
// 图片加载完处理
image.onload = function () {
var imgScale = imgScaleW(1000, this.width, this.height);
canvas.width = imgScale.width;
canvas.height = imgScale.height;
ctx.drawImage(image, 0, 0, imgScale.width, imgScale.height);
// 图片base64
var dataURL = canvas.toDataURL('image/jpeg');
// 清除画布
ctx.clearRect(0, 0, imgScale.width, imgScale.height);
//dataURL:处理成功返回的图片base64
backData(dataURL);
}
image.src = result;
};
reader.readAsDataURL(file);
}
// 创建画布
function createCanvas() {
var canvas = document.getElementById('canvas');
if (!canvas) {
var canvasTag = document.createElement('canvas');
canvasTag.setAttribute('id', 'canvas');
//隐藏画布
canvasTag.setAttribute('style', 'display:none;');
document.body.appendChild(canvasTag);
canvas = document.getElementById('canvas');
}
return canvas;
}
/**
* maxWidth:宽度或者高度最大值
* width:宽度
* height:高度
*/
function imgScaleW(maxWidth, width, height) {
var imgScale = {};
var w = 0;
var h = 0;
// 如果图片宽高都小于限制的最大值,不用缩放
if (width <= maxWidth && height <= maxWidth) {
imgScale = {
width: width,
height: height
}
} else {
if (width >= height) {
w = maxWidth;
h = Math.ceil(maxWidth * height / width);
} else {
h = maxWidth;
w = Math.ceil(maxWidth * width / height);
}
imgScale = {width: w,height: h}
}
return imgScale;
}
</script>
</body>
</html>