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

2022-08-30 04:36:24

我想在JS中动态更改背景,并且我的图像集采用base64编码。我尝试:

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

完美的结果,

然而,我无法对以下方面做同样的事情:

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

也不

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

有什么办法可以做到这一点吗?


答案 1

我试图像你一样做同样的事情,但显然背景图像不适用于编码数据。作为替代方案,我建议使用CSS类以及这些类之间的更改。

如果您“动态”生成数据,则可以动态加载CSS文件。

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

我在这里摆弄它,按下按钮,它将切换div的背景:http://jsfiddle.net/egorbatik/fFQC6/


答案 2

与base64有同样的问题。对于将来遇到相同问题的任何人:

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

这将从控制台执行,但不能从脚本中执行:

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

但是在玩了一会儿之后,我想出了这个:

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

不知道为什么它适用于代理映像,但它确实如此。在 Firefox Dev 37 和 Chrome 40 上进行了测试。

希望它能帮助别人。

编辑

进一步调查。似乎有时base64编码(至少在我的情况下)与CSS中断,因为编码值中存在换行符(在我的情况下,值是由ActionScript动态生成的)。

简单地使用,例如:

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

也可以工作,甚至似乎比使用代理映像快几毫秒。