首页 > 解决方案 > 使用画布将文件输入到 blob

问题描述

无法将 blob 插入 indexedDB 请协助将 blob 从文件插入 indexedDB :)

代码

    <html>
      <head>
        <title>file to BLOB</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      </head>
    <body>
      <div id="test">
        <input id="File" type="file" accept="image/*" capture="user">
      </div>
    </body>
    </html>
<script src="js/idbConn.js"></script>

Javascript

<script>
    $(document).ready(function(){
      $("#File").change(function(){
      const File = this.files[0];
      const cvs = document.createElement("canvas");
      const optBlob = cvs.toBlob(function(cvsBlob){
        let fileURL = URL.createObjectURL(File);
        let imgFile = new Image();
        let imgFile.src = fileURL;
        imgFile.onload = function(){
          cvs.width = imgFile.naturalWidth;
          cvs.height = imgFile.naturalHeight;
          let ctx = cvs.getContext("2d").drawImage(imgFile,0,0);
          URL.revokeObjectURL(fileURL);
        }
      },File.type,0.3);
      const data = new Object();
      data.blob = optBlob;
      let trx = db.transaction(["imgBlobs"],"readwrite").objectStore("imgBlobs").put(data,"test.jpeg");
      });
    });
</script>

试图直接将文件插入 indexedDB 但 blob 未定义

如果将 cvsBlob 保存在 data.blob 中,则空白图像存储在 indexedDB 中

标签: javascripthtmlimage-processingcanvas

解决方案


有几个问题。

  • HTMLCanvasElement.toBlob不返回任何东西。您在回调函数中获得了 blob。
  • JavaScript 是阻塞的,排队的任务(如toBlob回调)事件(如onload)在当前执行返回之前不会运行。这意味着该 const data = new Object();行在调用 toBlob 回调之前运行。
  • toBlob您在创建、加载图像并将其绘制到画布之前调用。
  • let imgFile.src = fileURL;这一行会抛出语法错误??

使固定

  • 首先加载图像。
  • 在图像加载时创建画布并在其上绘制图像。
  • 撤消图片网址。
  • 将画布转换为 blob。
  • toBlob回调中将 blob 添加到数据库。

例子

使用从文件输入中获得的文件调用该函数。例如 $("#File").change(function() { saveImageToDB(this.files[0]) });

function saveImageToDB(file) {
    const fileURL = URL.createObjectURL(file);
    const img = new Image();
    img.src = fileURL;
    img.addEventListener("load", () => {
        URL.revokeObjectURL(fileURL);
        const cvs = document.createElement("canvas");
        cvs.width = img.naturalWidth;
        cvs.height = img.naturalHeight;
        cvs.getContext("2d").drawImage(img, 0, 0);
        cvs.toBlob(blob => {
            // Code to add blob to database. Put your db code in here
            db.transaction(["img"], "write").objectStore("imgs").put({blob}, file.name);
        }, File.type, 0.3);
    }, {once: true});
}

推荐阅读