<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片获取base64以及压缩</title>
</head>
<body>
<div>
<input type="file" accept="image/*" name="file" id="file" onchange="checkPic(this)">
</div>
<div>
<img src="" alt="" id="img" class="img" style="width: 400px;">
<img src="" alt="" id="img1" class="img1" style="width: 400px;">
</div>
<script>
function checkPic(e) {
var file = e.files[0];
var name = file.name;
console.log("name:" + name);
var size = file.size;
console.log("size:" + size);
var type = file.type;
console.log("type:" + type);
var lastModifiedDate = file.lastModifiedDate;
console.log("lastModifiedDate:" + lastModifiedDate);
var lastModified = file.lastModified;
console.log("lastModified:" + lastModified);
var base64 = getBase64(file);
canvasDataURL("./../images/迪丽热巴 - 221.jpg");
}
//获取图片base64码
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function (e) {
var base64 = e.target.result;
console.log(e.target.result);
console.log(base64.length)
showPic(base64,"img");
};
}
//展示图片
function showPic(str,src) {
document.getElementById(src).setAttribute("src", str);
}
function canvasDataURL(path) {
var img = new Image();
img.src = path;
img.onload = function(){
var that = this;
// 默认按比例压缩
var w = that.width;
var h = that.height;
if(w > 1024){
w = w / 40;
h = h / 40;
}
var quality = 0.7; // 默认图片质量为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/png', quality);
// 回调函数返回base64的值
showPic(base64,"img1");
console.log(base64);
console.log(base64.length);
}
}
</script>
</body>
</html>
js图片获取base64以及压缩
最新推荐文章于 2024-05-29 15:01:33 发布