Completed
Pull Request — master (#132)
by Jace
01:42
created

Image.generate()   A

Complexity

Conditions 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2
Metric Value
cc 2
dl 0
loc 6
ccs 6
cts 6
cp 1
crap 2
rs 9.4286
1 1
import os
2 1
import logging
3
4 1
from PIL import Image as ImageFile, ImageFont, ImageDraw
0 ignored issues
show
Configuration introduced by
The import PIL could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
5
6
7 1
log = logging.getLogger(__name__)
8
9
# TODO: move to a fonts store
10 1
FONT = os.path.normpath(os.path.join(
11
    os.path.dirname(__file__), os.pardir, os.pardir,
12
    'data', 'fonts', 'Impact.ttf'
13
))
14
15
16 1
class Image:
17
    """JPEG generated by applying text to a template."""
18
19 1
    def __init__(self, template, text, style=None, root=None):
20 1
        self.template = template
21 1
        self.style = style
22 1
        self.text = text
23 1
        self.root = root
24
25 1
    @property
26
    def path(self):
27 1
        if not self.root:
28
            return None
29
30 1
        return os.path.join(
31
            self.root, self.template.key, self.text.path + '.jpg')
32
33 1
    def generate(self):
34 1
        directory = os.path.dirname(self.path)
35 1
        if not os.path.isdir(directory):
36 1
            os.makedirs(directory)
37 1
        background = self.template.get_path(self.style)
38 1
        make_meme(self.text.top, self.text.bottom, background, self.path)
39
40
41
# based on: https://github.com/danieldiekmeier/memegenerator
42 1
def make_meme(top, bottom, background, path, match_font_size=False):
43
    """Add text to an image and save it."""
44 1
    img = ImageFile.open(background)
45
46
    # Resize to a maximum height and width
47 1
    img.thumbnail((500, 500))
48 1
    image_size = img.size
49
50
    # Draw image
51 1
    draw = ImageDraw.Draw(img)
52
53 1
    max_font_size = int(image_size[1] / 5)
54 1
    min_font_size_single_line = int(image_size[1] / 12)
55 1
    max_text_len = image_size[0] - 20
56 1
    top_font_size, top = _optimize_font_size(top, max_font_size,
57
                                             min_font_size_single_line,
58
                                             max_text_len)
59 1
    bottom_font_size, bottom = _optimize_font_size(bottom, max_font_size,
60
                                                   min_font_size_single_line,
61
                                                   max_text_len)
62
63 1
    if match_font_size is True:
64
        top_font_size = min(top_font_size, bottom_font_size)
65
        bottom_font_size = top_font_size
66
67 1
    top_font = ImageFont.truetype(FONT, top_font_size)
68 1
    bottom_font = ImageFont.truetype(FONT, bottom_font_size)
69
70 1
    top_text_size = draw.multiline_textsize(top, top_font)
71 1
    bottom_text_size = draw.multiline_textsize(bottom, bottom_font)
72
73
    # Find top centered position for top text
74 1
    top_text_position_x = (image_size[0] / 2) - (top_text_size[0] / 2)
75 1
    top_text_position_y = 0
76 1
    top_text_position = (top_text_position_x, top_text_position_y)
77
78
    # Find bottom centered position for bottom text
79 1
    bottom_text_size_x = (image_size[0] / 2) - (bottom_text_size[0] / 2)
80 1
    bottom_text_size_y = image_size[1] - bottom_text_size[1] * (7 / 6)
81 1
    bottom_text_position = (bottom_text_size_x, bottom_text_size_y)
82
83 1
    _draw_outlined_text(draw, top_text_position,
84
                        top, top_font, top_font_size)
85 1
    _draw_outlined_text(draw, bottom_text_position,
86
                        bottom, bottom_font, bottom_font_size)
87
88 1
    log.info("Generating: %s", path)
89 1
    return img.save(path)
90
91
92 1
def _draw_outlined_text(draw_image, text_position, text, font, font_size):
93
    """Draw white text with black outline on an image."""
94
95
    # Draw black text outlines
96 1
    outline_range = max(1, font_size // 25)
97 1
    for x in range(-outline_range, outline_range + 1):
98 1
        for y in range(-outline_range, outline_range + 1):
99 1
            pos = (text_position[0] + x, text_position[1] + y)
100 1
            draw_image.multiline_text(pos, text, (0, 0, 0),
101
                                      font=font, align='center')
102
103
    # Draw inner white text
104 1
    draw_image.multiline_text(text_position, text, (255, 255, 255),
105
                              font=font, align='center')
106
107
108 1
def _optimize_font_size(text, max_font_size, min_font_size,
109
                        max_text_len):
110
    """Calculate the optimal font size to fit text in a given size."""
111
112
    # Check size when using smallest single line font size
113 1
    font = ImageFont.truetype(FONT, min_font_size)
114 1
    text_size = font.getsize(text)
115
116
    # Calculate font size for text, split if necessary
117 1
    if text_size[0] > max_text_len:
118 1
        phrases = _split(text)
119
    else:
120 1
        phrases = (text,)
121 1
    font_size = max_font_size // len(phrases)
122 1
    for phrase in phrases:
123 1
        font_size = min(_maximize_font_size(phrase, max_text_len),
124
                        font_size)
125
126
    # Rebuild text with new lines
127 1
    text = '\n'.join(phrases)
128
129 1
    return font_size, text
130
131
132 1
def _maximize_font_size(text, max_size):
133
    """Find the biggest font size that will fit."""
134 1
    font_size = max_size
135
136 1
    font = ImageFont.truetype(FONT, font_size)
137 1
    text_size = font.getsize(text)
138 1
    while text_size[0] > max_size and font_size > 1:
139 1
        font_size = font_size - 1
140 1
        font = ImageFont.truetype(FONT, font_size)
141 1
        text_size = font.getsize(text)
142
143 1
    return font_size
144
145
146 1
def _split(text):
147
    """Split a line of text into two similarly sized pieces.
148
149
    >>> _split("Hello, world!")
150
    ('Hello,', 'world!')
151
152
    >>> _split("This is a phrase that can be split.")
153
    ('This is a phrase', 'that can be split.')
154
155
    >>> _split("This_is_a_phrase_that_can_not_be_split.")
156
    ('This_is_a_phrase_that_can_not_be_split.',)
157
158
    """
159 1
    result = (text,)
160
161 1
    if len(text) >= 3 and ' ' in text[1:-1]:  # can split this string
162 1
        space_indices = [i for i in range(len(text)) if text[i] == ' ']
163 1
        space_proximities = [abs(i - len(text) // 2) for i in space_indices]
164 1
        for i, j in zip(space_proximities, space_indices):
165 1
            if i == min(space_proximities):
166 1
                result = (text[:j], text[j + 1:])
167 1
                break
168
169
    return result
170