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

后端 未结 9 2230
执念已碎
执念已碎 2020-12-02 16:09

I want to change background dynamically in JS and my set of images is in base64 encoded. I try:

document.getElementById(\"bg_image\").style.backgroundImage =         


        
相关标签:
9条回答
  • 2020-12-02 17:07

    In my case, it was just because I didn't set the height and width.

    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.

    0 讨论(0)
  • 2020-12-02 17:09

    Had the same problem with 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.

    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).

    Simply using e.g.:

    $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.

    0 讨论(0)
  • 2020-12-02 17:09

    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:

    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)
    
    0 讨论(0)
提交回复
热议问题