原创

js中多文件流转换


将canvas导出base64图片

<canvas id="canvas"></canvas>
<script>
  let cvs = document.createElement( 'canvas' );
  let ctx = cvs.getContext( '2d' );
  cvs.width = 100
  cvs.height = 100
  ctx.fillStyle = '#ffffff';
  ctx.fillRect( 0, 0, 100, 100 );
  // 把画布的内容转换为base64编码格式的图片
  let base64 = cvs.toDataURL( 'image/png', 1 );  //1表示质量(无损压缩)
  console.log(base64)
</script>

把canvas导出成Blob文件

canvas.toBlob(function (blob) {
    let reader = new FileReader();
    reader.readAsDataURL(blob, 'utf-8');
    reader.onload = function (e) {
        console.log(this.result);
    }
})

将base64转换为文件file对象

dataURLtoFile: function(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 });
	}

将文件file转换成base64

function readFile(file) {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
        let base64 = this.result
    }
}

base64转换为blob

function convertBase64ToBlob(base64) {
    let base64Arr = base64.split(',');
    let imgType = '';
    let base64String = '';
    if (base64Arr.length > 1) {
        //如果是图片base64,去掉头信息
        base64String = base64Arr[1];
        imgType = base64Arr[0].substring(base64Arr[0].indexOf(':') + 1, base64Arr[0].indexOf(';'));
    }
    let bytes = atob(base64String);
    let bytesCode = new ArrayBuffer(bytes.length);
    let byteArray = new Uint8Array(bytesCode);
    for (let i = 0; i < bytes.length; i++) {
        byteArray[i] = bytes.charCodeAt(i);
    }
    return new Blob([bytesCode], {type: imgType});
}

推荐一款图片压缩插件

插件名称:ls-compressimage
插件地址:https://www.npmjs.com/package/ls-compressimage
功能包含:图片压缩、修改图片大小、格式转换、file base64 blob相互转换

JavaScript
vue
  • 作者:零三(联系作者)
  • 最后更新时间:2020-06-21 15:51
  • 版权声明:自由转载-非商用-非衍生-保持署名
  • 转载声明:来源地址 https://web03.cn