图片上传转base64
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片转base64</title>
</head>
<body>
<input type='file' class='file'>
<div class="ImgBox"></div>
</body>
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(".file").change(function() {
var file = $(this)[0].files[0];
if (beforeUpload(file))
getBase64(file, imageUrl =>
console.log(imageUrl)
);
})
function getBase64(img, callback) {
const reader = new FileReader();
var image = new Image();
reader.readAsDataURL(img);
reader.addEventListener('load', () => {
//不压缩图片直接 callback(reader.result)
image.src = reader.result;
});
image.onload = function() {
// 缩放图片需要的canvas(也可以在DOM中直接定义canvas标签,这样就能把压缩完的图片不转base64也能直接显示出来)
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
// 图片原始尺寸
var originWidth = this.width;
var originHeight = this.height;
// 最大尺寸限制,可通过设置宽高来实现图片压缩程度
var maxWidth = 400,
maxHeight = 400;
// 目标尺寸
var targetWidth = originWidth,
targetHeight = originHeight;
// 图片尺寸超过300x300的限制
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
// canvas对图片进行缩放
canvas.width = targetWidth;
canvas.height = targetHeight;
// 清除画布
context.clearRect(0, 0, targetWidth, targetHeight);
// 图片压缩
context.drawImage(image, 0, 0, targetWidth, targetHeight);
/*第一个参数是创建的img对象;第二三个参数是左上角坐标,后面两个是画布区域宽高*/
//压缩后的图片转base64 url
/*canvas.toDataURL(mimeType, qualityArgument),mimeType 默认值是'image/png';
* qualityArgument表示导出的图片质量,只有导出为jpeg和webp格式的时候此参数才有效,默认值是0.92*/
var newUrl = canvas.toDataURL('image/jpeg', 0.92); //base64 格式
callback(newUrl)
//也可以把压缩后的图片转blob格式用于上传
// canvas.toBlob((blob)=>{
// console.log(blob)
// //把blob作为参数传给后端
// }, 'image/jpeg', 0.92)
}
}
function beforeUpload(file) {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
alert('您好,暂时只支持上传jpg和png文件!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
alert('图片尺寸太大了!');
}
return isJpgOrPng && isLt2M;
}
</script>
</html>