Skip to content

Instantly share code, notes, and snippets.

@gsw945
Last active January 27, 2022 07:07
Show Gist options
  • Save gsw945/3891cc79e295234141c23444191bcb3d to your computer and use it in GitHub Desktop.
Save gsw945/3891cc79e295234141c23444191bcb3d to your computer and use it in GitHub Desktop.
generate smallest png base64 string
import base64
from io import BytesIO
from PIL import Image
def smallest_png_base64():
with Image.new('RGBA', (1, 1), (0, 0, 0, 0)) as img:
with BytesIO() as buffer:
img.save(buffer, format='PNG')
data = buffer.getvalue()
png_base64 = base64.b64encode(data).decode('ascii')
return 'data:image/png;base64,{0}'.format(png_base64)
if __name__ == '__main__':
base64_png = smallest_png_base64()
print('base64_png:', base64_png)
print('len(base64_png):', len(base64_png))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment