如何将图像src从blob字符串转换为数据URI [英] How to convert a image src from a blob string to data URI

查看:1024
本文介绍了如何将图像src从blob字符串转换为数据URI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,用户可以将图像粘贴到内容可编辑的div中。当我得到图像时,src返回一个字符串。当我查看调试工具时,这就是我所看到的:

I have a page where the user can paste an image into a content editable div. When I get the image the src returns a string. When I look in debug tools this is what I see:

<img src="blob:http://www.example.com/3955202440-AeFf-4a9e-b82c-cae3822d96d4"/>

如何将其转换为基本64字符串?

How do I convert that to a base 64 string?

这是测试脚本, http:// jsfiddle.net/bt7BU/824/

// We start by checking if the browser supports the 
// Clipboard object. If not, we need to create a 
// contenteditable element that catches all pasted data 
if (!window.Clipboard) {
   var pasteCatcher = document.createElement("div");
    
   // Firefox allows images to be pasted into contenteditable elements
   pasteCatcher.setAttribute("contenteditable", "");
    
   // We can hide the element and append it to the body,
   pasteCatcher.style.opacity = 0.5;
   document.body.appendChild(pasteCatcher);
 
   // as long as we make sure it is always in focus
   pasteCatcher.focus();
   document.addEventListener("click", function() { pasteCatcher.focus(); });
} 
// Add the paste event listener
window.addEventListener("paste", pasteHandler);
 
/* Handle paste events */
function pasteHandler(e) {
   // We need to check if event.clipboardData is supported (Chrome)
   if (e.clipboardData) {
      // Get the items from the clipboard
      var items = e.clipboardData.items || e.clipboardData.files;
      var itemcount = items ? items.length : 0;
      pasteArea.value = "items found:"+itemcount;
      if (itemcount) {
         // Loop through all items, looking for any kind of image
         for (var i = 0; i < items.length; i++) {
            if (items[i].type.indexOf("image") !== -1) {
               // We need to represent the image as a file,
               var blob = items[i].getAsFile();
               // and use a URL or webkitURL (whichever is available to the browser)
               // to create a temporary URL to the object
               var URLObj = window.URL || window.webkitURL;
               var source = URLObj.createObjectURL(blob);
                
               // The URL can then be used as the source of an image
               createImage(source);
            }
         }
      } else {
   
       			console.log("no items found. checking input");

          // This is a cheap trick to make sure we read the data
          // AFTER it has been inserted.
          setTimeout(checkInput, 1);
       }
   // If we can't handle clipboard data directly (Firefox), 
   // we need to read what was pasted from the contenteditable element
   } else {
   
   console.log("checking input");
    
      // This is a cheap trick to make sure we read the data
      // AFTER it has been inserted.
      setTimeout(checkInput, 1);
   }
}
 
/* Parse the input in the paste catcher element */
function checkInput() {
   console.log("check input");
    
   // Store the pasted content in a variable
   var child = pasteCatcher.childNodes[0];
 
   // Clear the inner html to make sure we're always
   // getting the latest inserted content
   //pasteCatcher.innerHTML = "";
   //console.log( "clearing catcher");
   console.log(child);
    
   if (child) {
      // If the user pastes an image, the src attribute
      // will represent the image as a base64 encoded string.
      if (child.tagName === "IMG") {
         createImage(child.src);
         reader = new FileReader();
         reader.readAsDataURL(child.src);
         reader.loadend = function(e) {
         		console.log(e.target.result);
         }
      }
   }
}
 
/* Creates a new image from a given source */
function createImage(source) {
   var pastedImage = new Image();
   pastedImage.onload = function(e) {
      //pasteArea.text = pastedImage.src;
      console.log(1);
      console.log(e);
      loadImage.src = e.target.src;
      console.log(loadImage.src);
      
   }
   pastedImage.src = source;
}

<textarea id="pasteArea" placeholder="Paste Image Here"></textarea>
<img id="loadImage" />

我在Mac上的Safari中测试了这个。

I'm testing this in Safari on Mac.

推荐答案

由于blobURI是由浏览器自动生成的,您可以使用它,将生成的图像下载为新的Blob :

Since the blobURI is generated automatically by the browser, you can use this, which will download the produced image as a new Blob:

const toDataURL = url => fetch(url)
  .then(response => response.blob())
  .then(blob => new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.onerror = reject
    reader.readAsDataURL(blob)
  }))

然后在你的函数createImage(source){你可以打电话给它:

And then on your function createImage(source) { you can call it:

toDataURL(source)
  .then(dataUrl => {
    console.log('RESULT:', dataUrl)
})

这篇关于如何将图像src从blob字符串转换为数据URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆