gpt4 book ai didi

javascript - JavaScript 中的 Blob 对象转为 base64

转载 作者:行者123 更新时间:2023-12-03 02:06:37 24 4
gpt4 key购买 nike

我正在尝试实现一个粘贴处理程序以从用户的剪贴板获取图像。我希望它只在 Google Chrome 上运行,我不担心其他浏览器。

这是我在互联网上找到的方法的一部分,我正在尝试对其进行修改。

// Get the items from the clipboard
var items = e.clipboardData.items;
if (items) {
// 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);
createImage(source);
}
}
}

该方法有效,如果我使用“源”作为图像对象的 src,我可以显示图像。问题是谷歌浏览器中的图像源将是这样的: blob:http://localhost:8080/d1328e65-ade2-45b3-a814-107cc2842ef9

我需要将此图像发送到服务器,因此我想将其转换为base64版本。例如:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAArgAAAAjCAIAAADwnO7RAAAKMWlDQ1BJQ0MgUHJvZmlsZQAASImdlndUU9kWh8+9N71QkhCKlNBraFICSA29SJEuKjEJEErAkAAiNkRUcERRkaYIMijggKNDkbEiioUBUbHrBBlE1HFwFBuWSWStGd+8ee/Nm98f935rn73P3Wfvfda6AJD8gwXCTFgJgAyhWBTh58WIjYtnYAcBDPAAA2wA4HCzs0IW+EYCmQJ82IxsmRP4F726DiD5+yrTP4zBAP+flLlZIjEAUJiM5/L42VwZF8k4PVecJbdPyZi2NE3OMErOIlmCMlaTc/IsW3z2mWUPOfMyhDwZy3PO4mXw5Nwn4405Er6MkWAZF+cI+LkyviZjg3RJhkDGb+SxGXxONgAoktwu5nNTZGwtY5IoMoIt43kA4EjJX/DSL1jMzxPLD8XOzFouEiSniBkmXFOGjZMTi+HPz03ni8XM...iCIBWnh+P9w9C+9eMzvhCl1iOElK09ruc2wqGhfH/uKEV30FlJkmRZJklydFuW/FdwhYFCkCBBggQJEuS/gWC4FCRIkCBBggQZlmCgECRIkCBBggQZlmCgECRIkCBBggQZFmzhwoXXWoYgQYIECRIkyHUK5vF4rrUMQYIECRIkSJDrFHLktYOCBAkSJEiQIP/NkLt3777WMgT5thLstwoSJEiQ7zxYsEUhyJWxbdu2u++++1pLESRIkCBBvl6Csx6CBAkSJEiQIMPy3dkMOsg3T7A5KkiQIEG+8wQDhSBXTjBQCBIkSJDvPMGuhyBBggQJEiTIsFwXLQr9H6bOjtYeP2mONbOj2Hut9y6/x+nlJSBCQnXkgG3Brh8Q4lqbOpAmPDqUGShex9lPDlfB4sU5I97b/8kuevygYUgYsAksAPg9fkbDQN/e1kNvVw76nfYeiTCG6sjLd5fv58rsFmxRCBIkSJDvPP8f+HtxbDVRPI8AAAAASUVORK5CYII=

在第一段代码中,我有一个代表文件的 blob 对象。我尝试了几种方法,但没有得到正确的表示。我如何使用它来创建 Base64 表示?

最佳答案

Nick Retallack 在本页的回答 How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+?正是我想要的。

所以新的代码是:

var items = e.clipboardData.items;
if (items) {
// 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();

var reader = new FileReader();
reader.onload = function(event){
createImage(event.target.result); //event.target.results contains the base64 code to create the image.
};
reader.readAsDataURL(blob);//Convert the blob from clipboard to base64
}
}
}

关于javascript - JavaScript 中的 Blob 对象转为 base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11850970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com