简体   繁体   English

如何将图像 src url 转换为 blob

[英]how to convert image src url to blob

I wanted to convert an image to blob url I currently can do it if user uploads the image through an input tag but what I want is what if I had a src url for the image how can I get that image then convert that image to blob.我想将图像转换为 blob url 如果用户通过输入标签上传图像,我目前可以做到这一点,但我想要的是如果我有一个图像的 src url 我如何获取该图像然后将该图像转换为 blob . Thanks in advance.提前致谢。

EDIT: Someone suggested a similar question, I tried to apply a similar method but I am not getting a blob url back I have updated my code to show the following.编辑:有人提出了一个类似的问题,我尝试应用类似的方法,但我没有得到 blob url 我已经更新了我的代码以显示以下内容。

Suggested SO URL: convert image into blob using javascript建议的 SO URL: 使用 javascript 将图像转换为 blob

 //this works for when image is uploaded through an input tag const image_input = document.querySelector("#image_input"); image_input.addEventListener("change", function() { const reader = new FileReader(); reader.addEventListener("load", () => { const uploaded_image = reader.result; console.log(uploaded_image) }); reader.readAsDataURL(this.files[0]); }); //Suggested Method function loadXHR(url) { return new Promise(function(resolve, reject) { try { var xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.responseType = "blob"; xhr.onerror = function() { reject("Network error.") }; xhr.onload = function() { if (xhr.status === 200) { resolve(xhr.response) } else { reject("Loading error:" + xhr.statusText) } }; xhr.send(); } catch (err) { reject(err.message) } }); } //I want to get the image throught a src link the convert that to blob url //somthing like this //convert src to blob //console.log(blobUrl) const src = '../img/myImage.jpg' loadXHR(src).then(function(blob) { //I currently only get back an object with size and and type not the blob url it self console.log(blob) });
 <input type="file" title="" id="image_input">

Try this way.试试这个方法。

 const src = '../img/myImage.jpg' loadXHR(src).then(function(blob) { // Here blob is object, you need to convert it to base64 by using FileReader const reader = new FileReader(); reader.addEventListener("load", () => { const uploaded_image = reader.result; console.log(uploaded_image); }); reader.readAsDataURL(blob); });

 const src = '../img/myImage.jpg' 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) })) toDataURL(src).then(dataUrl => { console.log(dataUrl) })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM