预览效果:
不废话,贴源码:
f.getFileAsUrl = function(file, back) {
var reader = new FileReader();
// 读取文件base64
reader.readAsDataURL(file);
reader.onload = function(evt) {
// 导出文件地址
back(evt.target.result);
}
};
f.getBase64 = function(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
var dataURL = canvas.toDataURL("image/" + ext);
return dataURL;
};
f.zipImgBackUrl = function(base64Img, back, size) {
var c = document.createElement('canvas');
var ctx = c.getContext("2d");
var img = new Image();
img.src = base64Img;
img.onload = function() {
// 取到图片原始尺寸
var w = img.width;
var h = img.height;
if (size.width && size.height) {
if (size.width > size.height) {
size.height = false;
} else {
size.width = false;
}
}
if (!size) {
c.width = w;
c.height = h;
} else if (size.width) {
if (size.width < w) {
c.width = size.width;
c.height = h * size.width / w;
} else {
c.width = w;
c.height = h;
}
} else if (size.height) {
if (size.height < h) {
c.height = size.height;
c.width = w * size.height / h;
} else {
c.width = w;
c.height = h;
}
}
// 解决透明图片,出现黑色背景的问题
var opacityImg = new Image();
var base64 = localStorage.getItem('opacityImg');
var hasLocal = base64 && /^data:image/.test(base64);
if (hasLocal) {
opacityImg.src = base64;
} else {
opacityImg.src = '/images/opacity-bg.jpg';
}
opacityImg.onload = function() {
if (!hasLocal) {
base64 = f.getBase64(opacityImg);
localStorage.setItem('opacityImg', base64);
}
ctx.fillStyle = ctx.createPattern(opacityImg, 'repeat');
fillImg(ctx,c,img,back);
};
//如果opacityImg不存在,或者异常错误,不影响后续执行
opacityImg.onerror = function(){
ctx.fillStyle = '#f0f0f0';
fillImg(ctx,c,img,back);
};
function fillImg(ctx,c,img,back){
ctx.fillRect(0, 0, c.width, c.height);
// 根据设置的size,进行尺寸压缩
ctx.drawImage(img, 0, 0, w, h, 0, 0, c.width, c.height);
//对预览图进行质量压缩
var src = c.toDataURL("image/jpeg", 0.5);
// 导出base64的图片路径
back(src);
}
};
};
调用:
<input type="file">
<img src=""/>
<script>
var input = document.querySelectory('input[type="file"]');
var img = document.querySelectory('img');
input.addEventListener('change',function(e){
var file = e.target.files[0];
f.getFileAsUrl(file,function(oldSrc){
f.zipImgBackUrl(oldSrc,function(src){
img.src = src;
},{
width:100,
height:100
});
});
},false);
</script>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。