5 Star 1 Fork 0

wangzhiweik/shop-system

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
test2017-12-19.html 2.82 KB
一键复制 编辑 原始数据 按行查看 历史
xiefy0066 提交于 2017-12-19 21:58 . bug
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>压缩上传为base64</title>
<!--<script src="../src/jquery.min.js"></script>-->
</head>
<body >
<form id="form1" name="form1" method="post" action="">
<input type="file" name="fileToUpload" id="fileToUpload"/> <br />
<input type="text" name="compressValue" id="compressValue" style="display:none;" /><br/>
<input type="button" id='uploadBtn' value="上传" /><br/>
</form>
</body>
<script type="text/javascript">
//图片上传change事件
$('#fileToUpload').change(function(){
uploadBtnChange();
});
//提交click事件
$('#uploadBtn').click(function(){
var preview = document.getElementById('compressValue').value;
if(preview){
$.ajax({
url:"index.php",
type: "POST",
data:{'imgBase64':preview},
dataType:'json',
success:function(json) {
alert(json);
},
error:function(){
alert('操作失败,请跟技术联系');
}
});
}
});
function uploadBtnChange(){
var scope = this;
if(window.File && window.FileReader && window.FileList && window.Blob){
//获取上传file
var filefield = document.getElementById('fileToUpload'),
file = filefield.files[0];
//获取用于存放压缩后图片base64编码
var compressValue = document.getElementById('compressValue');
processfile(file,compressValue);
}else{
alert("此浏览器不完全支持压缩上传图片");
}
}
function processfile(file,compressValue) {
var reader = new FileReader();
reader.onload = function (event) {
var blob = new Blob([event.target.result]);
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob);
var image = new Image();
image.src = blobURL;
console.log(blobURL);
image.onload = function() {
var resized = resizeMe(image);
compressValue.value = resized;
}
};
reader.readAsArrayBuffer(file);
}
function resizeMe(img) {
//压缩的大小
var max_width = 1920;
var max_height = 1080;
var canvas = document.createElement('canvas');
var width = img.width;
var height = img.height;
if(width > height) {
if(width > max_width) {
height = Math.round(height *= max_width / width);
width = max_width;
}
}else{
if(height > max_height) {
width = Math.round(width *= max_height / height);
height = max_height;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
//压缩率
return canvas.toDataURL("image/jpeg",0.92);
}
</script>
</html>
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/jason_wangzhiwei/shop-system.git
git@gitee.com:jason_wangzhiwei/shop-system.git
jason_wangzhiwei
shop-system
shop-system
master

搜索帮助