获取JavaScript中的图片数据网址? [英] Get image data url in JavaScript?

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

问题描述

我有一个带有一些图像的常规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="anonymous"属性和服务器支持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.

您将需要创建具有正确尺寸的canvas元素,并使用drawImage函数复制图像数据.然后,您可以使用toDataURL函数获取数据:具有以64为基数编码的图像的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格式的图像在Firefox的旧版本(约3.5版)上不起作用,因此,如果要支持该功能,则需要检查兼容性.如果不支持编码,则默认为"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中的图片数据网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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