我试图编写脚本来按给定的百分比值调整图像文件的大小。我的脚本如下:
let canvas;
let array_WH = new Array();
let percent = 50;
let img = new Image();
$(function() {
function ff(height, width, percentage) {
var newHeight = height * (percentage / 100);
var newWidth = width * (percentage / 100);
return [newWidth, newHeight];
}
$("#file_select").change(function(e) {
var fileReader = new FileReader();
fileReader.onload = function(e) {
img.onload = function() {
array_WH = ff(img.width, img.height, percent);
console.log('old width: ' + img.width);
console.log('new width: ' + array_WH[0]);
width = array_WH[0];
height = array_WH[1];
if (canvas) return;
canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(this, 0, 0, width, height);
var canvasData = canvas.toDataURL();
this.src = canvasData;
console.log(canvasData.length * 3 / 4, ' bytes');
document.body.appendChild(this);
}
img.src = e.target.result;
}
fileReader.readAsDataURL(e.target.files[0]);
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<h1 class="logo">Upload Picture</h1>
<div id="upload_form_div">
<form id="upload_form" method="POST" enctype="multipart/form-data" action="upload">
<input type="file" name="file" capture="camera" id="file_select" />
</form>
</div>
<div id="loading" style="display:none;">
Uploading your picture...
</div>
你可以
FiddleJs
在这里演示。
假设百分比是50%,因此
function ff(height, width, percentage) {...}
假定返回新宽度旧宽度的一半,新高度旧高度的一半,因此,返回旧图像大小的一半。
但是,它并不能像预期的那样工作。我通过上传3.00MB(宽58000px,高3867px)的图像文件进行了测试,然后函数生成了9.5MB(宽1933px,高2900px)的新图像文件,这与1.5MB旧图像大小的一半的正确文件大小相差甚远。
如何更正函数以达到给定百分比的预期结果?谢谢。