How do you base-64 encode a PNG image for use in a data-uri in a CSS file?

前端 未结 6 1190
孤独总比滥情好
孤独总比滥情好 2020-11-28 06:47

I want to base-64 encode a PNG file, to include it in a data:url in my stylesheet. How can I do that?

I’m on a Mac, so something on the Unix command line would work

6条回答
  •  旧时难觅i
    2020-11-28 07:07

    This should do it in Unix:

    b64encode filename.png X | sed '1d;$d' | tr -d '\n' > b64encoded.png
    

    The encoded image produced by b64encode includes a header and footer and no line longer than 76 characters. This format is typical in SMTP communications.

    To make the encoded image embeddable in HTML/CSS, the sed and tr commands remove the header/footer (first & last lines) and all newlines, respectively.

    Then just simply use the long encoded string in HTML

    
    

    or in CSS

    url(data:image/png;base64,ENCODED_PNG)
    

提交回复
热议问题