获取JavaScript中的图片数据网址?

编程入门 行业动态 更新时间:2024-10-15 20:19:37
本文介绍了获取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中的图片数据网址?

本文发布于:2023-11-28 16:00:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643054.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:网址   数据   图片   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!