javascript 从img标签(与URL.createObjectURL相反的方法)获取图像数据(blob)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23068788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:16:07  来源:igfitidea点击:

Get image data from (blob) from the img tag (opposite method to URL.createObjectURL)

javascripthtmlimagedomfileapi

提问by bluszcz

Inside my HTML code I have following IMG tag:

在我的 HTML 代码中,我有以下 IMG 标签:

<img src="picture.png"  id="picture" />

I would like to create in image Blob object (https://developer.mozilla.org/en-US/docs/Web/API/Blob) (to use it further in FirefoxOS web activity) having it's uri ("picture.png"). I guess I need the method which works in opposite way to URL.createObjectURL:

我想在图像 Blob 对象(https://developer.mozilla.org/en-US/docs/Web/API/Blob)中创建(以在 FirefoxOS 网络活动中进一步使用它)拥有它的 uri(“picture.png ”)。我想我需要与 URL.createObjectURL 以相反方式工作的方法:

https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL

https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL

回答by Lyall

The Fetch API is now suitable, as used in the docs:

Fetch API 现在适用,如文档中所用:

Using_Fetch#Checking_that_the_fetch_was_successful

Using_Fetch#Checking_that_the_fetch_was_successful

https://developer.mozilla.org/en-US/docs/Web/API/Body/blob

https://developer.mozilla.org/en-US/docs/Web/API/Body/blob

Simply:

简单地:

fetch("picture.png")
.then(res => res.blob())
.then(blob => {
    // use blob...
});

回答by Rob W

If you don't need a byte-by-byte copy of the image (e.g. if you don't mind that jpg is converted to png), then you can draw the image on a <canvas>, and use .toBlob()to get a blob for it.

如果您不需要图像的逐字节副本(例如,如果您不介意将 jpg 转换为 png),那么您可以在 上绘制图像<canvas>,并使用它.toBlob()来获取 blob。

If you need the original data as a blob, or if the image is hosted at a different origin, then you can use the code at https://stackoverflow.com/a/21136980(for same-origin requests, just use x.open('GET', 'picture.png');).

如果您需要原始数据作为 blob,或者图像托管在不同的来源,那么您可以使用https://stackoverflow.com/a/21136980 上的代码(对于同源请求,只需使用x.open('GET', 'picture.png');)。