在 JavaScript 中获取图像数据 URL? [英] Get image data URL in JavaScript?

查看:35
本文介绍了在 JavaScript 中获取图像数据 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些图像的常规 HTML 页面(只是常规的 <img/> HTML 标签).我想获得他们的内容,最好是 base64 编码,而无需重新下载图像(即它已经被浏览器加载,所以现在我想要内容).

I have a regular HTML page with some images (just regular <img /> HTML tags). I'd like to get their content, base64 encoded preferably, without the need to redownload the image (ie. it's already loaded by the browser, so now I want the content).

我很想通过 Greasemonkey 和 Firefox 实现这一目标.

I'd love to achieve that with Greasemonkey and Firefox.

推荐答案

注意:这仅适用于图像来自与页面相同的域,或者具有 crossOrigin="匿名" 属性,服务器支持 CORS.它也不会给你原始文件,而是一个重新编码的版本.如果您需要结果与原始结果相同,请参阅 Kaiido 的回答.

Note: This only works if the image is from the same domain as the page, or has the crossOrigin="anonymous" attribute and the server supports CORS. It's also not going to give you the original file, but a re-encoded version. If you need the result to be identical to the original, see Kaiido's answer.

您需要创建一个具有正确尺寸的画布元素,并使用 drawImage 函数复制图像数据.然后您可以使用 toDataURL 函数来获取具有 base-64 编码图像的 data: url.请注意,图像必须完全加载,否则您将返回一个空的(黑色、透明)图像.

You will need to create a canvas element with the correct dimensions and copy the image data with the drawImage function. Then you can use the toDataURL function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.

应该是这样的.我从未编写过 Greasemonkey 脚本,因此您可能需要调整代码以在该环境中运行.

It would be something like this. I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to
    // guess the original format, but be aware the using "image/jpg"
    // will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image/(png|jpg);base64,/, "");
}

获取 JPEG 格式的图像不适用于旧版本(大约 3.5)的 Firefox,因此如果您想支持它,则需要检查兼容性.如果不支持编码,则默认为image/png".

Getting a JPEG-formatted image doesn't work on older versions (around 3.5) of Firefox, so if you want to support that, you'll need to check the compatibility. If the encoding is not supported, it will default to "image/png".

这篇关于在 JavaScript 中获取图像数据 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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