QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

手机号码,快捷登录

手机号码,快捷登录

查看: 4015|回复: 0

[HTML/CSS/JS] File、Blob、dataURL 和 canvas 的应用与转换

[复制链接]

等级头衔

积分成就    金币 : 2857
   泡泡 : 1516
   精华 : 6
   在线时间 : 1317 小时
   最后登录 : 2025-4-23

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老活跃会员

联系方式
发表于 2021-5-31 11:44:28 | 显示全部楼层 |阅读模式
一、 概念介绍2 G: I2 I# d: c7 M% R6 c7 m
1. File
) j2 ~' F+ U& h. e2 V: ^! j(1) 通常情况下, File 对象是来自用户在一个 input 元素上选择文件后返回的 FileList 对象,也可以是来自由拖放操作生成的 DataTransfer 对象,或者来自 HTMLCanvasElement 上的 mozGetAsFile() API。( a2 E" @5 u  l- q7 _
(2) File 对象是特殊类型的 Blob,且可以用在任意的 Blob 类型的 context 中。比如:FileReader, URL.createObjectURL(), createImageBitmap(), 及 XMLHttpRequest.send() 都能处理 Blob 和 File。
' }7 ~3 D/ \6 G5 F7 M2. Blob
% d6 V- J6 |( m4 L(1) Blob 对象表示一个不可变、原始数据的类文件对象。它的数据可以按文本或二进制的格式进行读取,也可以转换成 ReadableStream 来用于数据操作。
4 z- n3 I  Q: S1 X* J(2) Blob 表示的不一定是JavaScript原生格式的数据。File 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
/ A/ k) }- C; Q- s- f3. dataURL
+ n: L( L5 f% |, e& S9 R3 Y2 U(1) Data URLs,即前缀为 data: 协议的URL,其允许内容创建者向文档中嵌入小文件。+ g2 n7 i0 I5 R$ F% E& P( Z
(2) Data URLs 由四个部分组成:前缀(data:)、指示数据类型的MIME类型、如果非文本则为可选的base64标记、数据本身:data:[][;base64],+ `2 j* d& e* q, l% {
4. canvas
6 _6 C0 O8 j5 }/ X% q: t# U+ x" Z1 W(1) Canvas API 提供了一个通过JavaScript 和 HTML的 canvas 元素来绘制图形的方式。它可以用于动画、游戏画面、数据可视化、图片编辑以及实时视频处理等方面。" V6 w; {) q8 \( q4 f
1.jpg ; H8 t/ ~$ h4 `( p
二、相互转化. A1 k8 t9 E+ g2 k) t
1. File、Blob 转化成 dataURL
( g. c* _0 v7 c) Z       FileReader 对象允许 Web 应用程序异步读取文件(或原始数据缓冲区)内容,使用 File 或 Blob 对象指定要读取的文件或数据。7 }- `% Q: a4 j
function fileToDataURL(file) {
    let reader = new FileReader()
    reader.readAsDataURL(file)
    // reader 读取文件成功的回调
    reader.onload = function(e) {
      return reader.result
    }
}
2. dataURL(base64) 转化成 Blob(二进制)对象$ W$ a/ b$ I8 J& j* J: B7 V
function dataURLToBlob(fileDataURL) {
    let arr = fileDataURL.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})
}
3. File, Blob 文件数据绘制到 canvas' \- B: w* k: M  Q
// 思路:File, Blob ——> dataURL ——> canvas
 
function fileAndBlobToCanvas(fileDataURL) {
    let img = new Image()
    img.src = fileDataURL
    let canvas = document.createElement('canvas')
    if(!canvas.getContext) {
      alert('浏览器不支持canvas')
      return;
    }
    let ctx = canvas.getContext('2d')
    document.getElementById('container').appendChild(canvas)
    img.onload = function() {
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
    }
}
4. 从 canvas 中获取文件 dataURL% U/ ^: j  P# u1 I8 n3 ]) B. I0 S" m
function canvasToDataURL() {
    let canvas = document.createElement('canvas')
    let canvasDataURL = canvas.toDataURL('image/png', 1.0)
    return canvasDataURL
}
三、完整例子0 o% I& Z# A3 }0 K- L$ m+ J8 F2 \7 A- l
       可以点击这里在线预览
! C2 [7 a! x( H 2.jpg
. G/ E4 ^# X9 m3 ]9 a3 l3 `& Q
<!--
 * @information: datadURL File Blob canvas 的互相转化
 * 
 * File.prototype instanceof Blob === true
 * Blob.prototype instanceof Object === true
-->
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>datadURL File Blob canvas</title>
  <style>
    .body {
      text-align: center;
    }
    .img-box {
      margin: 20px 0;
    }
    #img {
      width: 60%;
    }
  </style>
</head>
<body>
  
  <div class="body">
 
    <div class="input-box">
      <input id="input" type="file" accept="image/png, image/jpeg" onchange="onChangeInput()">
    </div>
    
    <div class="img-box">
      img: 
      <img src="" alt="img" id="img">
    </div>
 
    <div class="canvas-box" id="canvas-box">
      canvas: 
    </div>
 
  </div>
 
 
<script>
  // 文件对象
  let file; 
  // 文件 base64 码
  let fileDataURL;
 
 
  /**
   * @information: 获取文件
   */
  function onChangeInput() {
    file = document.getElementById('input').files[0]
    console.log('file->', file)
    if(!FileReader) {
      alert('浏览器版本过低,请升级版本')
      return;
    }
    fileToDataURL()
  }
  
  /**
   * @information: 使用 FileReader 读取文件内容, File(二进制) ——> dataURL(base64)   Blob ——> dataURL 同理
   */
  function fileToDataURL() {
    let reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = function(e) {
      console.log('dataURL->', reader.result)
      fileDataURL = reader.result
      showImg()
      dataURLToBlob()
    }
  }
 
  /**
   * @information: 图片回显
   */
  function showImg() {
    let img = document.getElementById('img')
    img.src = fileDataURL
  }
 
  /**
   * @information: dataURL(base64) ——> Blob(二进制)对象
   */
  function dataURLToBlob() {
    let arr = fileDataURL.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while(n --) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    console.log('blob->', new Blob([u8arr], {type: mime}))
    fileAndBlobToCanvas()
    return new Blob([u8arr], {type: mime})
  }
 
  /**
   * @information: File, Blob 文件数据绘制到 canvas
   * 思路:File, Blob ——> dataURL ——> canvas
   */
  function fileAndBlobToCanvas() {
    let img = new Image()
    img.src = fileDataURL
    let canvas = document.createElement('canvas')
    if(!canvas.getContext) {
      alert('浏览器不支持canvas')
      return;
    }
    let ctx = canvas.getContext('2d')
    document.getElementById('canvas-box').appendChild(canvas)
    img.onload = function() {
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
      canvasToDataURL()
    }
  }
 
  /**
   * @information: 从 canvas 中获取文件 dataURL 
   */
  function canvasToDataURL() {
    let canvas = document.createElement('canvas')
    let canvasDataURL = canvas.toDataURL('image/png', 1.0)
    console.log('从 canvas 中获取文件 dataURL :', canvasDataURL)
  }
 
</script>
 
</body>
</html>
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号|渝公网安备50010502503914号 )

GMT+8, 2025-4-30 17:03

Powered by paopaomj X3.5 © 2016-2025 sitemap

快速回复 返回顶部 返回列表