Completed
Push — master ( 69cfd2...2dc0e9 )
by Jace
16:33 queued 04:48
created

Image.__init__()   A

Complexity

Conditions 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

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