0

I am trying to set a div's background to a base64 image dynamically. The base64 image itself is stored in a string variable, base64Image. I am using the following line of code.

$("#loadingAdImage").css("background-image", `url("${base64Image}")`);

When I inspect the the div element, I find that even though the line was executed, the div has no style attribute. I even tried the following.

$("#loadingAdImage").attr("style", `background-image: url('${base64Image}')`);

This time when I inspected the div element, I got the style attribute, but the image itself isn't displaying in the background. Does anyone know what's wrong?

3 Answers3

2

This should work, it shows the images as loaded :-

HTML

<div id="test">

JS

var pic = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfMAAAHyCAMAAADIj";
// the pic data should be a lot bigger, change it to whatever data you have //
var img = new Image();
img.src = pic;
$("#test").css("background-image", "url('" + img.src + "')");
JulesUK
  • 359
  • 2
  • 11
0

Use an img tag for #loadingAdImage

then use this code

    $("#loadingAdImage").attr("src", "data:image/png;base64, "+base64Image);
bguiz
  • 27,371
  • 47
  • 154
  • 243
Michael Rogers
  • 190
  • 1
  • 11
0

The only way I can think of where this would happen is for base64Image to contain a " character.

Any other value would set the property correctly given your code:

const sources = [
 "foo bar'¨^*-0+:.?/#`", // many "special" characters but no double quote
 "foo \"bar" // contains a double quote
];
const test = (index) => {
  const source = sources[index];
  console.log(
    { source,
      result: $("#test" + index).css("background-image", `url("${source}")`)
        .attr("style")
    }
  );
};
test(0);
test(1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test0"></div>
<div id="test1"></div>

So double check your base64Image value, and remove any " in there, it's not part of the base64 encoding characters and it has nothing to do in a base64 encoded data: URL.

Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • I checked the base64Image value. Unfortunately I did not find any quotes or newline characters to remove. – Michael S. Miller Mar 25 '22 at 15:19
  • Could you paste your code in a https://jsfiddle.net or a https://pastebin.com/ if it's too big even for jsfiddle? Also are you sure the code is actually ran without error to this point? – Kaiido Mar 25 '22 at 15:58
  • Using console.log I was able to confirm that it ran without error. Is it possible that the length of the base64 string might be a factor? It is pretty long. So long in fact that pastebin rejected the post on the basis that it looked like spam. – Michael S. Miller Mar 25 '22 at 19:03
  • No the length should not prevent the setting of the attribute. If you have a github account you can probably create a https://gist.github.com/ – Kaiido Mar 26 '22 at 00:33