<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>压缩图片demo</title>
</head>
<body>
<img id="img" src="">
<input id="file" type="file" onchange="compress()">
</body>
<script>
// 对图片进行压缩
function compress() {
if(typeof FileReader=='undifined') //判断浏览器是否支持filereader
{
result.innerHTML="<p>抱歉,你的浏览器不支持 FileReader</p>";
return false;
}
var file=document.getElementById("file").files[0];
if(!/image\/\w+/.test(file.type)) //判断获取的是否为图片文件
{
alert("请确保文件为图像文件");
return false;
}
fileObj = document.getElementById('file').files[0] //上传文件的对象
reader = new FileReader()
reader.readAsDataURL(fileObj)
reader.onload = function(e) {
image = new Image() //新建一个img标签(还没嵌入DOM节点)
image.src = e.target.result
image.onload = function() {
canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
imageWidth = image.width / 10, //压缩后图片的大小
imageHeight = image.height / 10,
data = ''
canvas.width = imageWidth
canvas.height = imageHeight
context.drawImage(image, 0, 0, imageWidth, imageHeight)
data = canvas.toDataURL('image/jpeg')
//压缩完成
document.getElementById('img').src = data
}
}
}
</script>
</html>
上面是压缩图片的案例,我 不想用按钮,想直接把“1.jpg”赋值给fileObj,请问该怎么办??