/*
<input type="file" onchange="getFile(this.files)" />
*/
var getFile = function(file){
var inputfile = file[0];
fileToCanvas(inputfile);
fileToImage(inputfile);
}
function fileToImage(file){
var reader = new FileReader();
reader.readAsDataURL(file);//读取图像文件 result 为 DataURL, DataURL 可直接 赋值给 img.src
reader.onload = function(event){
var img = document.getElementById("img").children[0];
img.src = event.target.result;//base64
}
}
function fileToCanvas(file){
var reader = new FileReader();
reader.readAsDataURL(file);//读取图像文件 result 为 DataURL, DataURL 可直接 赋值给 img.src
reader.onload = function(event){
var image = document.createElement('img');
image.src = event.target.result;
image.onload = function(){
var canvas = document.getElementById("canvas");
var imageCanvas = canvas.getContext("2d");
imageCanvas.drawImage(image, 0, 0,300,300);
canvasToImage(canvas);
}
}
}
function canvasToImage(canvas){
var image = document.createElement('img');
image.src = canvas.toDataURL("image/png");//base64
}
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
扩展知识点
String转Blob
//将字符串 转换成 Blob 对象
var blob = new Blob(["Hello World!"], {
type: 'text/plain'
});
console.info(blob); // Blob {size: 12, type: "text/plain"}
console.info(blob.slice(1, 3, 'text/plain')); // Blob {size: 2, type: "text/plain"}
Blob转String
//将字符串转换成 Blob对象
var blob = new Blob(['中文字符串'], {
type: 'text/plain'
});
//将Blob 对象转换成字符串
var reader = new FileReader();
reader.readAsText(blob, 'utf-8');
reader.onload = function (e) {
console.info(reader.result); // Hello World!
}
//将Blob 对象转换成字符串
var reader = new FileReader();
reader.readAsText(blob.slice(1, 3, 'text/plain'), 'utf-8');
reader.onload = function (e) {
console.info(reader.result); // el
}
ArrayBuffer 转 Blob
var buffer = new ArrayBuffer(32);
var blob = new Blob([buffer])
XLSX 页面导出
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<!--以下js地址自行修改-->
<script src="./xlsx.full.min.js"></script>
<script src="xlsx.utils.js"></script>
<!--调用FileSaver saveAs函数可以实现文件下载-->
<!--<script src="http://sheetjs.com/demos/Blob.js"></script>
<script src="http://sheetjs.com/demos/FileSaver.js"></script>-->
<script>
//如果使用 FileSaver.js 就不要同时使用以下函数
function saveAs(obj, fileName) {//当然可以自定义简单的下载文件实现方式
var tmpa = document.createElement("a");
tmpa.download = fileName || "下载";
tmpa.href = URL.createObjectURL(obj); //绑定a标签
tmpa.click(); //模拟点击实现下载
setTimeout(function () { //延时释放
URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
}, 100);
}
var jsono = [{ //测试数据
"id": 1,//A
"合并的列头1": "数据11",//B
"合并的列头2": "数据12",//C
"合并的列头3": "数据13",//D
"合并的列头4": "数据14",//E
}, {
"id": 2,
"合并的列头1": "数据21",
"合并的列头2": "数据22",
"合并的列头3": "数据23",
"合并的列头4": "数据24",
}];//....
const wopts = { bookType: 'xlsx', bookSST: true, type: 'binary' };//这里的数据是用来定义导出的格式类型
function downloadExl(data, type) {
var wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };
// wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(data);//通过json_to_sheet转成单页(Sheet)数据
data = xlsxUtils.format2Sheet(data);
data["B1"] = { t: "s", v: "asdad" };
data["!merges"] = [{//合并第一行数据[B1,C1,D1,E1]
s: {//s为开始
c: 1,//开始列
r: 0//开始取值范围
},
e: {//e结束
c: 4,//结束列
r: 0//结束范围
}
}];
wb=xlsxUtils.format2WB(data,'Sheet1');
// data["!ref"]="A1:E7";
// wb.Sheets['Sheet1'] = data;
saveAs(new Blob([s2ab(XLSX.write(wb, wopts))], { type: "application/octet-stream" }), "这里是下载的文件名" + '.' + (wopts.bookType == "biff2" ? "xls" : wopts.bookType));
}
function s2ab(s) {
if (typeof ArrayBuffer !== 'undefined') {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
} else {
var buf = new Array(s.length);
for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
}
</script>
<button onclick="downloadExl(jsono)">导出</button>
</body>
</html>
File to Blob
let file = e.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload=function(){
let obj = binaryFun(reader.result);
let blob = new Blob([obj.u8arr],{type:obj.mime});
let url = URL.createObjectURL(blob)
}
const binaryFun = binary => {
let arr = binary.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return {u8arr,mime}
}
String to Blob
//将字符串转换成 Blob对象
var blob = new Blob(['中文字符串'], {
type: 'text/plain'
});
//将Blob 对象转换成 ArrayBuffer
var reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onload = function (e) {
console.info(reader.result); //ArrayBuffer {}
var arrayBuffer = reader.result;
//经常会遇到的异常 Uncaught RangeError: byte length of Int16Array should be a multiple of 2
//var buf = new int16array(arrayBuffer);
//console.info(buf);
//将 ArrayBufferView 转换成Blob
var buf = new Uint8Array(arrayBuffer);
console.info(buf); //[228, 184, 173, 230, 150, 135, 229, 173, 151, 231, 172, 166, 228, 184, 178]
reader.readAsText(new Blob([buf]), 'utf-8');
reader.onload = function (res) {
console.info(res.result); //中文字符串
};
//将 ArrayBufferView 转换成Blob
var buf = new DataView(arrayBuffer);
console.info(buf); //DataView {}
reader.readAsText(new Blob([buf]), 'utf-8');
reader.onload = function (res) {
console.info(res.result); //中文字符串
};
}
div转svg
function div2svg() {
var divContent = document.getElementById("div").innerHTML;
var svg = "<svg xmlns='http://www.w3.org/2000/svg'" +
"<foreignObject width='100%' height='100%'>" +
"<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:16px;font-family:Helvetica'>" +
divContent +
"</div>" +
"</foreignObject>" +
"</svg>";
document.body.innerHTML = svg;
}
div2svg();
SVG to Image
function svg2img() {
var divContent = document.getElementById("div").innerHTML;
var data = "data:image/svg+xml," +
"<svg xmlns='http://www.w3.org/2000/svg'" +
"<foreignObject width='100%' height='100%'>" +
"<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:16px;font-family:Helvetica'>" +
divContent +
"</div>" +
"</foreignObject>" +
"</svg>";
var img = new Image();
img.src = data;
document.body.appendChild(img);
}
svg2img();
Svg to Canvas
function svg2canvas() {
// 图片
var divContent = document.getElementById("div").innerHTML;
var data = "data:image/svg+xml," +
"<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
"<foreignObject width='100%' height='100%'>" +
"<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:16px;font-family:Helvetica'>" +
divContent +
"</div>" +
"</foreignObject>" +
"</svg>";
var img = new Image();
img.src = data;
img.onload = function () {
// canvas
var canvas = document.createElement('canvas'); //准备空画布
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d'); //取得画布的2d绘图上下文
context.drawImage(img, 0, 0);
document.body.appendChild(canvas);
}
}
svg2canvas();
videoToImg
var video = document.getElementById("j_video");
video.oncanplaythrough = function () {
// 保证能拿到正确的宽高 clientWidth clientHeight
VideoToImage(video);
}
function VideoToImage(video) {
const canvas = document.createElement("canvas");
canvas.width = video.width || video.clientWidth;
canvas.height = video.height || video.clientHeight;
canvas.style.position = "fixed";
canvas.style.left = "100%";
var context = canvas.getContext('2d'); //取得画布的2d绘图上下文
context.drawImage(video, 0, 0, canvas.width, canvas.height);
document.body.appendChild(canvas);
// canvasToImage(canvas);
const base64Data = canvas.toDataURL("image/png");
const a = document.createElement("a");
a.download = base64Data;
a.href = base64Data;
a.click();
document.body.removeChild(canvas);
}
function canvasToImage(canvas){
var image = document.createElement('img');
image.src = canvas.toDataURL("image/png"); // base64
}
Blob to Base64
function blobToDataURL(blob, callback) {
let a = new FileReader();
a.onload = function (e) { callback(e.target.result); }
a.readAsDataURL(blob);
}
Base64 to Blob
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
ImgToBase64
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("img");
img.src = "xxx.png"
// 注意非同源的图片会抛出此异常
// Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
img.onload = function() {
ctx.drawImage(img,0,0);
var dataURL = c.toDataURL();
console.log(dataURL);
}