Completed
Pull Request — master (#391)
by Jace
08:05
created

Image.path()   A

Complexity

Conditions 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3.0123

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
dl 0
loc 14
ccs 8
cts 9
cp 0.8889
crap 3.0123
rs 9.4285
c 1
b 0
f 0
1 1
import os
2 1
import hashlib
3 1
import logging
4
5 1
from PIL import Image as ImageFile, ImageFont, ImageDraw, ImageFilter
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...
6
7
8 1
log = logging.getLogger(__name__)
9
10
11 1
class Image(object):
12
    """JPEG generated by applying text to a template."""
13
14 1
    def __init__(self, template, text, root=None,
15
                 style=None, font=None, size=None, watermark=""):
16 1
        self.root = root
17 1
        self.template = template
18 1
        self.style = style
19 1
        self.text = text
20 1
        self.font = font
21 1
        self.width = size.get('width') if size else None
22 1
        self.height = size.get('height') if size else None
23 1
        self.watermark = watermark
24
25 1
    @property
26
    def path(self):
27 1
        if not self.root:
28
            return None
29
30 1
        base = os.path.join(self.root, self.template.key, self.text.path)
31 1
        custom = [self.style, self.font,
32
                  self.width, self.height, self.watermark]
33
34 1
        if any(custom):
35 1
            slug = self.hash(custom)
36 1
            return "{}#{}.img".format(base, slug)
37
        else:
38 1
            return base + ".img"
39
40 1
    @staticmethod
41
    def hash(values):
42 1
        sha = hashlib.md5()
43 1
        for index, value in enumerate(values):
44 1
            sha.update("{}:{}".format(index, value or "").encode('utf-8'))
45 1
        return sha.hexdigest()
46
47 1
    def save(self):
48 1
        data = _generate(
49
            top=self.text.top, bottom=self.text.bottom,
50
            font=self.font.path,
51
            background=self.template.get_path(self.style),
52
            width=self.width, height=self.height,
53
            watermark=self.watermark,
54
        )
55
56 1
        directory = os.path.dirname(self.path)
57 1
        if not os.path.isdir(directory):
58 1
            os.makedirs(directory)
59
60 1
        log.info("Saving image: %s", self.path)
61 1
        path = data.save(self.path, format=data.format)
62
63 1
        return path
64
65
66 1
def _generate(top, bottom, font, background, width, height, watermark):
67
    """Add text to an image and save it."""
68 1
    log.info("Loading background: %s", background)
69 1
    background_image = ImageFile.open(background)
70 1
    if background_image.mode not in ('RGB', 'RGBA'):
71 1
        if background_image.format == 'JPEG':
72 1
            background_image = background_image.convert('RGB')
73 1
            background_image.format = 'JPEG'
74
        else:
75 1
            background_image = background_image.convert('RGBA')
76 1
            background_image.format = 'PNG'
77
78
    # Resize to a maximum height and width
79 1
    ratio = background_image.size[0] / background_image.size[1]
80 1
    if width and height:
81 1
        if width < height * ratio:
82 1
            dimensions = width, int(width / ratio)
83
        else:
84 1
            dimensions = int(height * ratio), height
85 1
    elif width:
86 1
        dimensions = width, int(width / ratio)
87 1
    elif height:
88 1
        dimensions = int(height * ratio), height
89
    else:
90 1
        dimensions = 600, int(600 / ratio)
91 1
    image = background_image.resize(dimensions, ImageFile.LANCZOS)
92 1
    image.format = 'PNG'
93
94
    # Draw image
95 1
    draw = ImageDraw.Draw(image)
96
97 1
    max_font_size = int(image.size[1] / 5)
98 1
    min_font_size_single_line = int(image.size[1] / 12)
99 1
    max_text_len = image.size[0] - 20
100 1
    top_font_size, top = _optimize_font_size(font, top, max_font_size,
101
                                             min_font_size_single_line,
102
                                             max_text_len)
103 1
    bottom_font_size, bottom = _optimize_font_size(font, bottom, max_font_size,
104
                                                   min_font_size_single_line,
105
                                                   max_text_len)
106
107 1
    top_font = ImageFont.truetype(font, top_font_size)
108 1
    bottom_font = ImageFont.truetype(font, bottom_font_size)
109
110 1
    top_text_size = draw.multiline_textsize(top, top_font)
111 1
    bottom_text_size = draw.multiline_textsize(bottom, bottom_font)
112
113
    # Find top centered position for top text
114 1
    top_text_position_x = (image.size[0] / 2) - (top_text_size[0] / 2)
115 1
    top_text_position_y = 0
116 1
    top_text_position = (top_text_position_x, top_text_position_y)
117
118
    # Find bottom centered position for bottom text
119 1
    bottom_text_size_x = (image.size[0] / 2) - (bottom_text_size[0] / 2)
120 1
    bottom_text_size_y = image.size[1] - bottom_text_size[1] * (7 / 6)
121 1
    bottom_text_position = (bottom_text_size_x, bottom_text_size_y)
122
123 1
    _draw_outlined_text(draw, top_text_position,
124
                        top, top_font, top_font_size)
125 1
    _draw_outlined_text(draw, bottom_text_position,
126
                        bottom, bottom_font, bottom_font_size)
127
128
    # Pad image if a specific dimension is requested
129 1
    if width and height:
130 1
        image = _add_blurred_background(image, background_image, width, height)
131
132
    # Add watermark
133 1
    if watermark:
134 1
        draw = ImageDraw.Draw(image)
135 1
        watermark_font = ImageFont.truetype(font, 15)
136 1
        _draw_outlined_text(draw, (3, image.size[1] - 20),
137
                            watermark, watermark_font, 15)
138
139 1
    return image
140
141
142 1
def _optimize_font_size(font, text, max_font_size, min_font_size,
143
                        max_text_len):
144
    """Calculate the optimal font size to fit text in a given size."""
145
146
    # Check size when using smallest single line font size
147 1
    fontobj = ImageFont.truetype(font, min_font_size)
148 1
    text_size = fontobj.getsize(text)
149
150
    # Calculate font size for text, split if necessary
151 1
    if text_size[0] > max_text_len:
152 1
        phrases = _split(text)
153
    else:
154 1
        phrases = (text,)
155 1
    font_size = max_font_size // len(phrases)
156 1
    for phrase in phrases:
157 1
        font_size = min(_maximize_font_size(font, phrase, max_text_len),
158
                        font_size)
159
160
    # Rebuild text with new lines
161 1
    text = '\n'.join(phrases)
162
163 1
    return font_size, text
164
165
166 1
def _draw_outlined_text(draw_image, text_position, text, font, font_size):
167
    """Draw white text with black outline on an image."""
168
169
    # Draw black text outlines
170 1
    outline_range = max(1, font_size // 25)
171 1
    for x in range(-outline_range, outline_range + 1):
172 1
        for y in range(-outline_range, outline_range + 1):
173 1
            pos = (text_position[0] + x, text_position[1] + y)
174 1
            draw_image.multiline_text(pos, text, (0, 0, 0),
175
                                      font=font, align='center')
176
177
    # Draw inner white text
178 1
    draw_image.multiline_text(text_position, text, (255, 255, 255),
179
                              font=font, align='center')
180
181
182 1
def _add_blurred_background(foreground, background, width, height):
183
    """Add a blurred background to match the requested dimensions."""
184 1
    base_width, base_height = foreground.size
185
186 1
    border_width = min(width, base_width + 2)
187 1
    border_height = min(height, base_height + 2)
188 1
    border_dimensions = border_width, border_height
189 1
    border = ImageFile.new('RGB', border_dimensions)
190 1
    border.paste(foreground, ((border_width - base_width) // 2,
191
                              (border_height - base_height) // 2))
192
193 1
    padded_dimensions = (width, height)
194 1
    padded = background.resize(padded_dimensions, ImageFile.LANCZOS)
195
196 1
    darkened = padded.point(lambda p: p * 0.4)
197
198 1
    blurred = darkened.filter(ImageFilter.GaussianBlur(5))
199 1
    blurred.format = 'PNG'
200
201 1
    blurred_width, blurred_height = blurred.size
202 1
    offset = ((blurred_width - border_width) // 2,
203
              (blurred_height - border_height) // 2)
204 1
    blurred.paste(border, offset)
205
206 1
    return blurred
207
208
209 1
def _maximize_font_size(font, text, max_size):
210
    """Find the biggest font size that will fit."""
211 1
    font_size = max_size
212
213 1
    fontobj = ImageFont.truetype(font, font_size)
214 1
    text_size = fontobj.getsize(text)
215 1
    while text_size[0] > max_size and font_size > 1:
216 1
        font_size = font_size - 1
217 1
        fontobj = ImageFont.truetype(font, font_size)
218 1
        text_size = fontobj.getsize(text)
219
220 1
    return font_size
221
222
223 1
def _split(text):
224
    """Split a line of text into two similarly sized pieces.
225
226
    >>> _split("Hello, world!")
227
    ('Hello,', 'world!')
228
229
    >>> _split("This is a phrase that can be split.")
230
    ('This is a phrase', 'that can be split.')
231
232
    >>> _split("This_is_a_phrase_that_can_not_be_split.")
233
    ('This_is_a_phrase_that_can_not_be_split.',)
234
235
    """
236 1
    result = (text,)
237
238 1
    if len(text) >= 3 and ' ' in text[1:-1]:  # can split this string
239 1
        space_indices = [i for i in range(len(text)) if text[i] == ' ']
240 1
        space_proximities = [abs(i - len(text) // 2) for i in space_indices]
241 1
        for i, j in zip(space_proximities, space_indices):
242 1
            if i == min(space_proximities):
243 1
                result = (text[:j], text[j + 1:])
244 1
                break
245
246
    return result
247