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

This should do it in Python: import base64 binary_fc = open(filepath, ‘rb’).read() # fc aka file_content base64_utf8_str = base64.b64encode(binary_fc).decode(‘utf-8’) ext = filepath.split(‘.’)[-1] dataurl = f’data:image/{ext};base64,{base64_utf8_str}’ Thanks to @cnst comment, we need the prefix data:image/{ext};base64, Thanks to @ramazanpolat answer, we need the decode(‘utf-8’)

Remove trailing “=” when base64 encoding

The = is padding. <!————> Wikipedia says An additional pad character is allocated which may be used to force the encoded output into an integer multiple of 4 characters (or equivalently when the unencoded binary text is not a multiple of 3 bytes) ; these padding characters must then be discarded when decoding but still …

Read more

Save base64 string as PDF at client side with JavaScript

you can use this function to download file from base64. function downloadPDF(pdf) { const linkSource = `data:application/pdf;base64,${pdf}`; const downloadLink = document.createElement(“a”); const fileName = “abc.pdf”; downloadLink.href = linkSource; downloadLink.download = fileName; downloadLink.click();} This code will made an anchor tag with href and download file. if you want to use button then you can call click …

Read more