-
Notifications
You must be signed in to change notification settings - Fork 0
/
images.py
59 lines (44 loc) · 1.53 KB
/
images.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
Utilities to generate and manipulate images
"""
# This file is originally a part of https://github.com/qwiglydee/otree-advanced-demos
# SPDX-FileCopyrightText: © 2024 Maxim Vasilyev <[email protected]>
# SPDX-License-Identifier: MIT
from io import BytesIO
from base64 import b64decode, b64encode
MSG_NEED_PIL = """
FAILURE: Before using these real-effort tasks,
You need to:
(1) run "pip install Pillow"
(2) add Pillow to your requirements.txt
"""
try:
from PIL import Image, ImageDraw, ImageFont
except ImportError:
import sys
sys.tracebacklimit = 0
raise SystemExit(MSG_NEED_PIL)
def encode(image: Image):
buf = BytesIO()
image.save(buf, "PNG")
buf64 = b64encode(buf.getvalue())
return "data:image/png;base64," + buf64.decode('ascii')
def decode(dataurl: str):
assert dataurl.startswith("data:image/png;base64,")
buf64 = b64decode(dataurl[21:])
buf = BytesIO(buf64)
image = Image.open(buf)
return image
def font(filename, size):
return ImageFont.truetype(str(filename), size)
def text(text, font, size, *, padding=0, color="#000000", bgcolor="#FFFFFF"):
dumb = Image.new("RGB", (0, 0))
w, h = ImageDraw.ImageDraw(dumb).textsize(text, font)
image = Image.new("RGBA", (w + padding * 2, h + padding * 2), bgcolor)
draw = ImageDraw.Draw(image)
draw.text((padding, padding), text, font=font, fill=color)
return image
def distort(image, k=8):
w, h = image.size
image = image.resize((w//k, h//k), Image.BILINEAR).resize((w, h), Image.BILINEAR)
return image