1. /*
  2. <input type="file" onchange="getFile(this.files)" />
  3. */
  4. var getFile = function(file){
  5. var inputfile = file[0];
  6. fileToCanvas(inputfile);
  7. fileToImage(inputfile);
  8. }
  9. function fileToImage(file){
  10. var reader = new FileReader();
  11. reader.readAsDataURL(file);//读取图像文件 result 为 DataURL, DataURL 可直接 赋值给 img.src
  12. reader.onload = function(event){
  13. var img = document.getElementById("img").children[0];
  14. img.src = event.target.result;//base64
  15. }
  16. }
  17. function fileToCanvas(file){
  18. var reader = new FileReader();
  19. reader.readAsDataURL(file);//读取图像文件 result 为 DataURL, DataURL 可直接 赋值给 img.src
  20. reader.onload = function(event){
  21. var image = document.createElement('img');
  22. image.src = event.target.result;
  23. image.onload = function(){
  24. var canvas = document.getElementById("canvas");
  25. var imageCanvas = canvas.getContext("2d");
  26. imageCanvas.drawImage(image, 0, 0,300,300);
  27. canvasToImage(canvas);
  28. }
  29. }
  30. }
  31. function canvasToImage(canvas){
  32. var image = document.createElement('img');
  33. image.src = canvas.toDataURL("image/png");//base64
  34. }
  35. function dataURLtoBlob(dataurl) {
  36. var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
  37. bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  38. while(n--){
  39. u8arr[n] = bstr.charCodeAt(n);
  40. }
  41. return new Blob([u8arr], {type:mime});
  42. }
  43. function dataURLtoFile(dataurl, filename) {
  44. var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
  45. bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  46. while(n--){
  47. u8arr[n] = bstr.charCodeAt(n);
  48. }
  49. return new File([u8arr], filename, {type:mime});
  50. }

扩展知识点

Blob以及ArrayBuffer

String转Blob

  1. //将字符串 转换成 Blob 对象
  2. var blob = new Blob(["Hello World!"], {
  3. type: 'text/plain'
  4. });
  5. console.info(blob); // Blob {size: 12, type: "text/plain"}
  6. console.info(blob.slice(1, 3, 'text/plain')); // Blob {size: 2, type: "text/plain"}

Blob转String

  1. //将字符串转换成 Blob对象
  2. var blob = new Blob(['中文字符串'], {
  3. type: 'text/plain'
  4. });
  5. //将Blob 对象转换成字符串
  6. var reader = new FileReader();
  7. reader.readAsText(blob, 'utf-8');
  8. reader.onload = function (e) {
  9. console.info(reader.result); // Hello World!
  10. }
  11. //将Blob 对象转换成字符串
  12. var reader = new FileReader();
  13. reader.readAsText(blob.slice(1, 3, 'text/plain'), 'utf-8');
  14. reader.onload = function (e) {
  15. console.info(reader.result); // el
  16. }

ArrayBuffer 转 Blob

  1. var buffer = new ArrayBuffer(32);
  2. var blob = new Blob([buffer])

XLSX 页面导出

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <!--以下js地址自行修改-->
  9. <script src="./xlsx.full.min.js"></script>
  10. <script src="xlsx.utils.js"></script>
  11. <!--调用FileSaver saveAs函数可以实现文件下载-->
  12. <!--<script src="http://sheetjs.com/demos/Blob.js"></script>
  13. <script src="http://sheetjs.com/demos/FileSaver.js"></script>-->
  14. <script>
  15. //如果使用 FileSaver.js 就不要同时使用以下函数
  16. function saveAs(obj, fileName) {//当然可以自定义简单的下载文件实现方式
  17. var tmpa = document.createElement("a");
  18. tmpa.download = fileName || "下载";
  19. tmpa.href = URL.createObjectURL(obj); //绑定a标签
  20. tmpa.click(); //模拟点击实现下载
  21. setTimeout(function () { //延时释放
  22. URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
  23. }, 100);
  24. }
  25. var jsono = [{ //测试数据
  26. "id": 1,//A
  27. "合并的列头1": "数据11",//B
  28. "合并的列头2": "数据12",//C
  29. "合并的列头3": "数据13",//D
  30. "合并的列头4": "数据14",//E
  31. }, {
  32. "id": 2,
  33. "合并的列头1": "数据21",
  34. "合并的列头2": "数据22",
  35. "合并的列头3": "数据23",
  36. "合并的列头4": "数据24",
  37. }];//....
  38. const wopts = { bookType: 'xlsx', bookSST: true, type: 'binary' };//这里的数据是用来定义导出的格式类型
  39. function downloadExl(data, type) {
  40. var wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };
  41. // wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(data);//通过json_to_sheet转成单页(Sheet)数据
  42. data = xlsxUtils.format2Sheet(data);
  43. data["B1"] = { t: "s", v: "asdad" };
  44. data["!merges"] = [{//合并第一行数据[B1,C1,D1,E1]
  45. s: {//s为开始
  46. c: 1,//开始列
  47. r: 0//开始取值范围
  48. },
  49. e: {//e结束
  50. c: 4,//结束列
  51. r: 0//结束范围
  52. }
  53. }];
  54. wb=xlsxUtils.format2WB(data,'Sheet1');
  55. // data["!ref"]="A1:E7";
  56. // wb.Sheets['Sheet1'] = data;
  57. saveAs(new Blob([s2ab(XLSX.write(wb, wopts))], { type: "application/octet-stream" }), "这里是下载的文件名" + '.' + (wopts.bookType == "biff2" ? "xls" : wopts.bookType));
  58. }
  59. function s2ab(s) {
  60. if (typeof ArrayBuffer !== 'undefined') {
  61. var buf = new ArrayBuffer(s.length);
  62. var view = new Uint8Array(buf);
  63. for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  64. return buf;
  65. } else {
  66. var buf = new Array(s.length);
  67. for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
  68. return buf;
  69. }
  70. }
  71. </script>
  72. <button onclick="downloadExl(jsono)">导出</button>
  73. </body>
  74. </html>

File to Blob

  1. let file = e.target.files[0];
  2. let reader = new FileReader();
  3. reader.readAsDataURL(file);
  4. reader.onload=function(){
  5. let obj = binaryFun(reader.result);
  6. let blob = new Blob([obj.u8arr],{type:obj.mime});
  7. let url = URL.createObjectURL(blob)
  8. }
  9. const binaryFun = binary => {
  10. let arr = binary.split(','), mime = arr[0].match(/:(.*?);/)[1],
  11. bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  12. while(n--){
  13. u8arr[n] = bstr.charCodeAt(n);
  14. }
  15. return {u8arr,mime}
  16. }

String to Blob

  1. //将字符串转换成 Blob对象
  2. var blob = new Blob(['中文字符串'], {
  3. type: 'text/plain'
  4. });
  5. //将Blob 对象转换成 ArrayBuffer
  6. var reader = new FileReader();
  7. reader.readAsArrayBuffer(blob);
  8. reader.onload = function (e) {
  9. console.info(reader.result); //ArrayBuffer {}
  10. var arrayBuffer = reader.result;
  11. //经常会遇到的异常 Uncaught RangeError: byte length of Int16Array should be a multiple of 2
  12. //var buf = new int16array(arrayBuffer);
  13. //console.info(buf);
  14. //将 ArrayBufferView 转换成Blob
  15. var buf = new Uint8Array(arrayBuffer);
  16. console.info(buf); //[228, 184, 173, 230, 150, 135, 229, 173, 151, 231, 172, 166, 228, 184, 178]
  17. reader.readAsText(new Blob([buf]), 'utf-8');
  18. reader.onload = function (res) {
  19. console.info(res.result); //中文字符串
  20. };
  21. //将 ArrayBufferView 转换成Blob
  22. var buf = new DataView(arrayBuffer);
  23. console.info(buf); //DataView {}
  24. reader.readAsText(new Blob([buf]), 'utf-8');
  25. reader.onload = function (res) {
  26. console.info(res.result); //中文字符串
  27. };
  28. }

div转svg

  1. function div2svg() {
  2. var divContent = document.getElementById("div").innerHTML;
  3. var svg = "<svg xmlns='http://www.w3.org/2000/svg'" +
  4. "<foreignObject width='100%' height='100%'>" +
  5. "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:16px;font-family:Helvetica'>" +
  6. divContent +
  7. "</div>" +
  8. "</foreignObject>" +
  9. "</svg>";
  10. document.body.innerHTML = svg;
  11. }
  12. div2svg();

SVG to Image

  1. function svg2img() {
  2. var divContent = document.getElementById("div").innerHTML;
  3. var data = "data:image/svg+xml," +
  4. "<svg xmlns='http://www.w3.org/2000/svg'" +
  5. "<foreignObject width='100%' height='100%'>" +
  6. "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:16px;font-family:Helvetica'>" +
  7. divContent +
  8. "</div>" +
  9. "</foreignObject>" +
  10. "</svg>";
  11. var img = new Image();
  12. img.src = data;
  13. document.body.appendChild(img);
  14. }
  15. svg2img();

Svg to Canvas

  1. function svg2canvas() {
  2. // 图片
  3. var divContent = document.getElementById("div").innerHTML;
  4. var data = "data:image/svg+xml," +
  5. "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
  6. "<foreignObject width='100%' height='100%'>" +
  7. "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:16px;font-family:Helvetica'>" +
  8. divContent +
  9. "</div>" +
  10. "</foreignObject>" +
  11. "</svg>";
  12. var img = new Image();
  13. img.src = data;
  14. img.onload = function () {
  15. // canvas
  16. var canvas = document.createElement('canvas'); //准备空画布
  17. canvas.width = img.width;
  18. canvas.height = img.height;
  19. var context = canvas.getContext('2d'); //取得画布的2d绘图上下文
  20. context.drawImage(img, 0, 0);
  21. document.body.appendChild(canvas);
  22. }
  23. }
  24. svg2canvas();

videoToImg

  1. var video = document.getElementById("j_video");
  2. video.oncanplaythrough = function () {
  3. // 保证能拿到正确的宽高 clientWidth clientHeight
  4. VideoToImage(video);
  5. }
  6. function VideoToImage(video) {
  7. const canvas = document.createElement("canvas");
  8. canvas.width = video.width || video.clientWidth;
  9. canvas.height = video.height || video.clientHeight;
  10. canvas.style.position = "fixed";
  11. canvas.style.left = "100%";
  12. var context = canvas.getContext('2d'); //取得画布的2d绘图上下文
  13. context.drawImage(video, 0, 0, canvas.width, canvas.height);
  14. document.body.appendChild(canvas);
  15. // canvasToImage(canvas);
  16. const base64Data = canvas.toDataURL("image/png");
  17. const a = document.createElement("a");
  18. a.download = base64Data;
  19. a.href = base64Data;
  20. a.click();
  21. document.body.removeChild(canvas);
  22. }
  23. function canvasToImage(canvas){
  24. var image = document.createElement('img');
  25. image.src = canvas.toDataURL("image/png"); // base64
  26. }

Blob to Base64

  1. function blobToDataURL(blob, callback) {
  2. let a = new FileReader();
  3. a.onload = function (e) { callback(e.target.result); }
  4. a.readAsDataURL(blob);
  5. }

Base64 to Blob

  1. function dataURLtoBlob(dataurl) {
  2. var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
  3. bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  4. while (n--) {
  5. u8arr[n] = bstr.charCodeAt(n);
  6. }
  7. return new Blob([u8arr], { type: mime });
  8. }

ImgToBase64

  1. var c=document.getElementById("myCanvas");
  2. var ctx=c.getContext("2d");
  3. var img=document.getElementById("img");
  4. img.src = "xxx.png"
  5. // 注意非同源的图片会抛出此异常
  6. // Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
  7. img.onload = function() {
  8. ctx.drawImage(img,0,0);
  9. var dataURL = c.toDataURL();
  10. console.log(dataURL);
  11. }