前端图片canvas,file,blob,DataURL等格式转换

From: http://www.javashuo.com/article/p-ptcwhjdk-s.htmljavascript

 

将file转化成base64

  • 方法一:利用URL.createObjectURL()
复制代码
 1 <!DOCTYPE html>  2 <html>  3 <head>  4 <title>base</title>  5 </head>  6 <body>  7 <input type="file" name="" id="file">  8 <img src="" id="img">  9 <script type="text/javascript"> 10  window.onload = function () { 11  let $img = document.getElementById('img') 12  file.onchange = function (e) { 13  console.log(e.target.files[0]) 14  let file = e.target.files[0] 15  let fileUrl = window.URL.createObjectURL(file) 16  $img.src = fileUrl 17  img.onload = function () { 18 // 手动回收 19  URL.revokeObjectURL(fileUrl) 20  } 21  } 22  } 23 </script> 24 </body> 25 </html>
复制代码

当选择图片后,生成的img src相似"blob:null/4304d4f3-c13b-43e8-83f6-8c80426520ff",能正常显示图片。html

  • 方法二: 利用FileReader.readAsDataURL()
复制代码
<!DOCTYPE html> <html> <head> <title>base</title> </head> <body> <input type="file" name="" id="file"> <img src="" id="img"> <script type="text/javascript"> window.onload = function () { let $img = document.getElementById('img') file.onchange = function (e) { console.log(e.target.files[0]) let file = e.target.files[0] const fr = new FileReader(file) fr.readAsDataURL(file) fr.onload = function () { $img.src = this.result } } } </script> </body> </html>
复制代码

img标签的src将会是像这样:"data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAABkCAYAAADDhn8LAAA==,可以正常显示。java

 

canvas 转为DataURL

 

场景: canvas画出来的图片,在html中的其余地方显示。这里的方法也是能够将canvas输出为Dataurl的来放到img标签中。canvas

 

let imgSrc = canvas.toDataURL('image/png')
// canvas.toDataURL('image/jpeg')

canvas转为blob对象

 

场景: canvas生成的图片,如何上传到七牛云或服务器?答案是将canvas输出为Blob对象,这样就能够像File对象同样操做它了。服务器

 

 canvas.toBlob(function (blobObj) { console.log(blobObj) })
 canvas.toBlob还有两个参数一个是名称name,另外一个是压缩质量quality 0~1

Blob对象显示图片

 

场景: 获取到的图片是Blob格式的,如何显示在html中?答案仍是将Blob对象转换为DataUrl的形式。this

 

canvas.toBlob(function (blobObj) { let imgSrc = window.URL.createObjectURL(blobObj) document.getElementById('img').src = imgSrc })

下载DataURL表示的图片

 

场景: html中一张用DataURL形式显示出来的图片,能够下载到本地吗?答案是使用一个a标签,并设置download属性,模拟点击。url

复制代码
function downloadImg () { let aLink = document.createElement('a') aLink.download = 'fileName.png' // 文件名后缀须要和dataurl表示的相同,不然可能乱码 aLink.href = dataUrl aLink.click() }
复制代码
相关文章
相关标签/搜索