简体   繁体   English

有没有办法将背景图像设置为 base64 编码图像?

[英]Is there a way to set background-image as a base64 encoded image?

I want to change background dynamically in JS and my set of images is in base64 encoded.我想在 JS 中动态更改背景,并且我的图像集采用 base64 编码。 I try:我尝试:

document.getElementById("bg_image").style.backgroundImage = 
   "url('http://amigo.com/300107-2853.jpg')"; 

with perfect result,以完美的结果,

yet I fail to do the same with:但我没有做同样的事情:

document.getElementById("bg_image").style.backgroundImage = 
   "url('data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...')";

nor也不

document.getElementById("bg_image").style.backgroundImage = 
   "data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...";

Is there any way to do it?有什么办法吗?

I tried to do the same as you, but apparently the backgroundImage doesn't work with encoded data.我试图和你做同样的事情,但显然 backgroundImage 不适用于编码数据。 As an alternative, I suggest to use CSS classes and the change between those classes.作为替代方案,我建议使用 CSS 类以及这些类之间的更改。

If you are generating the data "on the fly" you can load the CSS files dynamically.如果您正在“即时”生成数据,您可以动态加载 CSS 文件。

CSS: CSS:

.backgroundA {
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXN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4p2tGrJZeH9y79mZsawFoaIRxF3JyiYxuHiMGb5KTkpFvZj4ZbYeCiXaOiKBwnxh4fnt9e3ktgZyHhrChinONs3cFAShFF2JhvCZlG5uchYNun5eedRxMAF15XEFRXgZWWdciuM8GCmdSQ84lLQfY5R14wDB5Lyon4ubwS7jx9NcV9/j5+g4JADs=");
}

HTML: HTML:

<div id="test" height="20px" class="backgroundA"> 
  div test 1
</div>
<div id="test2" name="test2" height="20px" class="backgroundB">
  div test2
</div>
<input type="button" id="btn" />

Javascript: Javascript:

function change() {
    if (document.getElementById("test").className =="backgroundA") {
        document.getElementById("test").className="backgroundB";
        document.getElementById("test2").className="backgroundA";
    } else {
        document.getElementById("test").className="backgroundA";
        document.getElementById("test2").className="backgroundB";
    }
}

btn.onclick= change;

I fiddled it here, press the button and it will switch the divs' backgrounds: http://jsfiddle.net/egorbatik/fFQC6/我在这里摆弄它,按下按钮,它会切换 div 的背景: http : //jsfiddle.net/egorbatik/fFQC6/

Had the same problem with base64. base64 也有同样的问题。 For anyone in the future with the same problem:对于将来遇到相同问题的任何人:

url = "data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...";

This would work executed from console, but not from within a script:这可以从控制台执行,但不能从脚本中执行:

$img.css("background-image", "url('" + url + "')");

But after playing with it a bit, I came up with this:但是在玩了一会儿之后,我想出了这个:

var img = new Image();
img.src = url;
$img.css("background-image", "url('" + img.src + "')");

No idea why it works with a proxy image, but it does.不知道为什么它适用于代理图像,但确实如此。 Tested on Firefox Dev 37 and Chrome 40.在 Firefox Dev 37 和 Chrome 40 上测试。

Hope it helps someone.希望它可以帮助某人。

EDIT编辑

Investigated a little bit further.稍微调查了一下。 It appears that sometimes base64 encoding (at least in my case) breaks with CSS because of line breaks present in the encoded value (in my case value was generated dynamically by ActionScript).似乎有时 base64 编码(至少在我的情况下)由于编码值中存在换行符而与 CSS 中断(在我的情况下,值是由 ActionScript 动态生成的)。

Simply using eg:简单地使用例如:

$img.css("background-image", "url('" + url.replace(/(\r\n|\n|\r)/gm, "") + "')");

works too, and even seems to be faster by a few ms than using a proxy image.也可以工作,甚至似乎比使用代理图像快几毫秒。

试试这个,我得到了成功的回应..它正在工作

$("#divId").css("background-image", "url('data:image/png;base64," + base64String + "')");

Adding this trick to gabriel garcia's following solution -将此技巧添加到 gabriel garcia 的以下解决方案中 -

var img = 'data:image/png;base64, ...'; //place ur base64 encoded img here
document.body.style.backgroundImage = 'url(' + img + ')';

However, in my case this wasn't working.但是,就我而言,这不起作用。 Moving url into the img variable did the trick.将 url 移动到 img 变量中就行了。 SO the final code looked like this所以最终的代码看起来像这样

var img = "url('data:image/png;base64, "+base64Data + "')";
document.body.style.backgroundImage = img; 

I tried this (and worked for me):我试过这个(并为我工作):

var img = 'data:image/png;base64, ...'; //place ur base64 encoded img here
document.body.style.backgroundImage = 'url(\'' + img + '\')';

ES6 syntax: ES6 语法:

let img = 'data:image/png;base64, ...'
document.body.style.backgroundImage = `url('${img}')`

A bit better:好一些:

let setBackground = src => {
    this.style.backgroundImage = `url('${src}')`
};

let node = nodeIGotFromDOM, img = imageBase64EncodedFromMyGF;
setBackground.call(node, img);

This is the correct way to make a pure call.这是进行纯调用的正确方法。 No CSS.没有 CSS。

<div style='background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAFCAYAAABW1IzHAAAAHklEQVQokWNgGPaAkZHxPyMj439sYrSQo51PBgsAALa0ECF30JSdAAAAAElFTkSuQmCC)repeat-x center;'></div>

I think this will help, Base64 is addressed by CSS in a different way, you should set the data type of the image to base64, this will help the CSS to change the base64 to image and display it to the user.我认为这会有所帮助,Base64 由 CSS 以不同的方式处理,您应该将图像的数据类型设置为 base64,这将有助于 CSS 将 base64 更改为图像并将其显示给用户。 and you can use this from javascript by assigning the background image using the jquery script, it will automatically change the base64 to mage and display it并且您可以通过使用 jquery 脚本分配背景图像来从 javascript 中使用它,它会自动将 base64 更改为 mage 并显示它

 url = "data:image;base64,"+data.replace(/(\\r\\n|\\n|\\r)/gm, ""); $("body").css("background-image", "url('" + url.replace(/(\\r\\n|\\n|\\r)/gm, "") + "')");

What I usually do, is to store the full string into a variable first, like so:我通常做的是首先将完整字符串存储到变量中,如下所示:

<?php
$img_id = 'data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAY...';
?>

Then, where I want either JS to do something with that variable:然后,我希望 JS 对那个变量做一些事情:

<script type="text/javascript">
document.getElementById("img_id").backgroundImage="url('<?php echo $img_id; ?>')";
</script>

You could reference the same variable via PHP directly using something like:您可以使用以下内容通过 PHP 直接引用相同的变量:

<img src="<?php echo $img_id; ?>">

Works for me ;)为我工作;)

Do not use quotes inside url when using data URIs .不要使用引号内的url当使用数据URI

li {
  background:
    url(data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7)
    no-repeat
    left center;
  padding: 5px 0 5px 25px;
}

In my case, it was just because I didn't set the height and width .就我而言,这只是因为我没有设置heightwidth

But there is another issue.但还有一个问题。

The background image could be removed using可以使用删除背景图像

element.style.backgroundImage=""

but couldn't be set using但无法设置使用

element.style.backgroundImage="some base64 data"

Jquery works fine. Jquery 工作正常。

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

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