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

前端 未结 6 1197
孤独总比滥情好
孤独总比滥情好 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条回答
  •  孤街浪徒
    2020-11-28 07:22

    import base64
    
    def image_to_data_url(filename):
        ext = filename.split('.')[-1]
        prefix = f'data:image/{ext};base64,'
        with open(filename, 'rb') as f:
            img = f.read()
        return prefix + base64.b64encode(img).decode('utf-8')
    

提交回复
热议问题