js 预览图片 转base64
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>files-h5</title> </head> <body> <input type="file" id="file" onchange="showPreview(this, 'portrait')" /> <img src="" id="portrait" style="width: 200px; height: 200px; display: block;" /> <script> function showPreview(source, imgId) { var file = source.files[0]; //获取文件 //FileReader对象获取 if(window.FileReader) { var fr = new FileReader(); //文件加载后触发 fr.onloadend = function(e) { document.getElementById(imgId).src = e.target.result; } //读取这个文件 fr.readAsDataURL(file); } } </script> <script> /* img标签到base64 var img =document.getElementById("ak"); 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); console.log(dataURL); */ /* 直接解析base64编码 var t1 =t.FaceInfoList[0].FaceImage.Data; // t1= /9j/4AAQSk......Wn1aYz//Z var str0 =t1;//.replace(/\ /g, ''); console.log('data:image/jpg;base64,'+ str0); document.getElementById('img').src='data:image/jpg;base64,'+ str0; */ /* 方法2 用 createObjectURL url = window.URL.createObjectURL(file.files[0]); } document.getElementById(imgId).src = url; */ /* 方法3 数组 方法 outputImg.src = 'data:image/png;base64,' + arrayBufferToBase64(obj.arry); function arrayBufferToBase64(buffer) { var binary = ''; var bytes = new Uint8Array(buffer); var len = bytes.byteLength; for (var i = 0; i < len; i++) { binary += String.fromCharCode(bytes[i]); } return window.btoa(binary);//编码 } C# byte[] bytes = vCode.get_bmp(code); string str = bytes.ToJsonString(); 在控制器 HOME/P_Getcode() */ </script> </body> </html>
转自 https://segmentfault.com/q/1010000019122380/a-1020000019123433