文章字数:290,阅读全文大约需要1分钟
封装了几个方法,主要是传入input对象,将对象选中的文件转程base64形式。可以用于图片上传,图片选中后马上显示等功能
1.读取input对象图片,并调用2执行压缩
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
function inputImgToBase64(inputOb,outputFun) { var file=inputOb.files[0]
if(!/image\/\w+/.test(file.type)) { alert("请确保文件为图像文件"); return false; } var reader=new FileReader(); reader.readAsDataURL(file); reader.onload=function(e) { var image = new Image(); image.imgType = file.type; var fileNameList = file.name.split('.'); var fileType = fileNameList[fileNameList.length-1]; $('#photoType').attr('value',fileType);
image.src = e.target.result; image.onload = function() { var expectWidth = 480; var expectHeight = 640; var base64 = compress(this,expectWidth,expectHeight,1); outputFun(base64); } } }
|
2.图片转base64
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
function compress(img, width, height, ratio) { var canvas, ctx, img64; canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, width, height); img64 = canvas.toDataURL(img.imgType, ratio); return img64; }
|
使用方式
1 2 3 4
| inputImgToBase64($('#inputPhoto')[0],function (base64) { $('#output')[0].src=base64 });
|