summaryrefslogtreecommitdiff
path: root/postgresqleu/util/image.py
blob: f681982e92e5ed0914633145a5e4a7df06ff1f3c (plain)
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
import io

from PIL import Image, ImageFile


# Rescale an image in the form of bytes to a new set of bytes
# in the same format. Assumes the aspect is correct and that
# the incoming data is valid (it's expected to be for example
# the output of previous image operations)
def rescale_image_bytes(origbytes, resolution):
    p = ImageFile.Parser()
    p.feed(origbytes)
    p.close()
    img = p.image

    return rescale_image(img, resolution)


def rescale_image(img, resolution, centered=False):
    scale = min(
        float(resolution[0]) / float(img.size[0]),
        float(resolution[1]) / float(img.size[1]),
    )

    newimg = img.resize(
        (int(img.size[0] * scale), int(img.size[1] * scale)),
        Image.BICUBIC,
    )
    saver = io.BytesIO()
    if centered and newimg.size[0] != newimg.size[1]:
        # This is not a square, so we have to roll it again
        centeredimg = Image.new('RGBA', resolution)
        centeredimg.paste(newimg, (
            (resolution[0] - newimg.size[0]) // 2,
            (resolution[1] - newimg.size[1]) // 2,
        ))
        centeredimg.save(saver, format='PNG')
    else:
        newimg.save(saver, format=img.format)

    return saver.getvalue()


def get_image_contenttype_from_bytes(image):
    if bytearray(image[:3]) == b'\xFF\xD8\xFF':
        return 'image/jpeg'
    elif bytearray(image[:8]) == b'\x89\x50\x4e\x47\x0d\x0a\x1a\x0a':
        return 'image/png'
    raise Exception("Could not determine image format")