1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from __future__ import unicode_literals
9 from PIL import Image, ImageFont, ImageDraw, ImageFilter
10 from six import BytesIO
11 from librarian import get_resource, OutputFile, URLOpener
15 """Gets metrics from an object, scaling it by a factor."""
16 def __init__(self, obj, scale):
18 self._scale = float(scale)
20 def __getattr__(self, name):
21 src = getattr(self._obj, name)
22 if src and self._scale:
23 return type(src)(self._scale * src)
28 class TextBox(object):
29 """Creates an Image with a series of centered strings."""
35 def __init__(self, max_width, max_height, padding_x=None, padding_y=None):
37 padding_x = self.SHADOW_X + self.SHADOW_BLUR
39 padding_y = self.SHADOW_Y + self.SHADOW_BLUR
41 self.max_width = max_width
42 self.max_text_width = max_width - 2 * padding_x
43 self.padding_y = padding_y
44 self.height = padding_y
45 self.img = Image.new('RGBA', (max_width, max_height))
46 self.draw = ImageDraw.Draw(self.img)
47 self.shadow_img = None
48 self.shadow_draw = None
50 def skip(self, height):
51 """Skips some vertical space."""
54 def text(self, text, color='#000', font=None, line_height=20,
56 """Writes some centered text."""
57 text = re.sub(r'\s+', ' ', text)
59 if not self.shadow_img:
60 self.shadow_img = Image.new('RGBA', self.img.size)
61 self.shadow_draw = ImageDraw.Draw(self.shadow_img)
64 line_width = self.draw.textsize(line, font=font)[0]
65 while line_width > self.max_text_width:
66 parts = line.rsplit(' ', 1)
68 line_width = self.max_text_width
71 line_width = self.draw.textsize(line, font=font)[0]
72 line = line.strip() + ' '
74 pos_x = (self.max_width - line_width) // 2
77 self.shadow_draw.text(
78 (pos_x + self.SHADOW_X, self.height + self.SHADOW_Y),
79 line, font=font, fill=shadow_color
82 self.draw.text((pos_x, self.height), line, font=font, fill=color)
83 self.height += line_height
85 text = text[len(line):]
88 """Creates the actual Image object."""
89 image = Image.new('RGBA', (self.max_width,
90 self.height + self.padding_y))
92 shadow = self.shadow_img.filter(ImageFilter.BLUR)
93 image.paste(shadow, (0, 0), shadow)
94 image.paste(self.img, (0, 0), self.img)
96 image.paste(self.img, (0, 0))
101 """Abstract base class for cover images generator."""
104 background_color = '#fff'
105 background_img = None
108 author_margin_left = 20
109 author_margin_right = 20
111 author_color = '#000'
113 author_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
114 author_font_size = 30
117 title_margin_left = 20
118 title_margin_right = 20
122 title_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
127 uses_dc_cover = False
139 'JPEG': 'image/jpeg',
143 def __init__(self, book_info, format=None, width=None, height=None):
144 self.authors = [auth.readable() for auth in book_info.authors]
145 self.title = book_info.title
146 if format is not None:
149 self.height = int(round(height * self.width / width))
150 scale = max(float(width or 0) / self.width, float(height or 0) / self.height)
154 self.scale_after = scale
156 def pretty_authors(self):
157 """Allows for decorating authors' names."""
158 return [self.authors]
160 def pretty_title(self):
161 """Allows for decorating title."""
165 metr = Metric(self, self.scale)
166 img = Image.new('RGB', (metr.width, metr.height), self.background_color)
168 if self.background_img:
169 background = Image.open(self.background_img)
170 img.paste(background, None, background)
175 logo = Image.open(get_resource('res/wl-logo.png'))
176 logo = logo.resize((metr.logo_width, int(round(logo.size[1] * metr.logo_width / logo.size[0]))))
177 img.paste(logo, ((metr.width - metr.logo_width) // 2, img.size[1] - logo.size[1] - metr.logo_bottom))
179 top = metr.author_top
181 metr.width - metr.author_margin_left - metr.author_margin_right,
185 author_font = ImageFont.truetype(
186 self.author_font_ttf, metr.author_font_size)
187 for pa in self.pretty_authors():
188 tbox.text(pa, self.author_color, author_font, metr.author_lineskip, self.author_shadow)
189 text_img = tbox.image()
190 img.paste(text_img, (metr.author_margin_left, top), text_img)
192 top += text_img.size[1] + metr.title_top
194 metr.width - metr.title_margin_left - metr.title_margin_right,
197 title_font = ImageFont.truetype(
198 self.title_font_ttf, metr.title_font_size)
199 tbox.text(self.pretty_title(), self.title_color, title_font, metr.title_lineskip, self.title_shadow)
200 text_img = tbox.image()
201 img.paste(text_img, (metr.title_margin_left, top), text_img)
205 def final_image(self):
207 if self.scale_after != 1:
209 int(round(img.size[0] * self.scale_after)),
210 int(round(img.size[1] * self.scale_after))),
215 return self.mime_types[self.format]
218 return self.exts[self.format]
220 def save(self, *args, **kwargs):
222 'format': self.format,
225 default_kwargs.update(kwargs)
226 return self.final_image().save(*args, **default_kwargs)
228 def output_file(self, *args, **kwargs):
230 self.save(imgstr, *args, **kwargs)
231 return OutputFile.from_bytes(imgstr.getvalue())
234 class WLCover(Cover):
235 """Wolne Lektury cover without logos."""
239 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
240 author_font_size = 20
242 title_font_ttf = get_resource('fonts/DejaVuSerif-Bold.ttf')
245 title_box_width = 350
248 box_bottom_margin = 100
261 box_position = 'middle'
262 background_color = '#444'
263 author_color = '#444'
264 background_img = get_resource('res/cover.png')
268 u'Starożytność': '#9e3610',
269 u'Średniowiecze': '#564c09',
270 u'Renesans': '#8ca629',
272 u'Oświecenie': '#f2802e',
273 u'Romantyzm': '#db4b16',
274 u'Pozytywizm': '#961060',
275 u'Modernizm': '#7784e0',
276 u'Dwudziestolecie międzywojenne': '#3044cf',
277 u'Współczesność': '#06393d',
280 kind_box_position = {
285 def __init__(self, book_info, format=None, width=None, height=None, bleed=0):
286 super(WLCover, self).__init__(book_info, format=format, width=width, height=height)
288 self.box_position = book_info.cover_box_position or \
289 self.kind_box_position.get(book_info.kind, self.box_position)
291 if book_info.cover_bar_color == 'none':
294 self.bar_color = book_info.cover_bar_color or \
295 self.epoch_colors.get(book_info.epoch, self.bar_color)
297 self.title_color = self.epoch_colors.get(book_info.epoch, self.title_color)
300 self.box_top_margin += bleed
301 self.box_bottom_margin += bleed
302 self.bar_width += bleed
304 if book_info.cover_url:
305 url = book_info.cover_url
308 bg_src = URLOpener().open(url)
309 self.background_img = BytesIO(bg_src.read())
312 def pretty_authors(self):
313 return [a.upper() for a in self.authors]
315 def add_box(self, img):
316 if self.box_position == 'none':
319 metr = Metric(self, self.scale)
322 box = TextBox(metr.title_box_width, metr.height, padding_y=metr.box_padding_y)
323 author_font = ImageFont.truetype(
324 self.author_font_ttf, metr.author_font_size)
325 for pa in self.pretty_authors():
328 line_height=metr.author_lineskip,
329 color=self.author_color,
330 shadow_color=self.author_shadow)
332 box.skip(metr.box_above_line)
333 box.draw.line((metr.box_line_left, box.height, metr.box_line_right, box.height),
334 fill=self.author_color, width=metr.box_line_width)
335 box.skip(metr.box_below_line)
338 title_font = ImageFont.truetype(
339 self.title_font_ttf, metr.title_font_size)
340 box.text(self.pretty_title(),
341 line_height=metr.title_lineskip,
343 color=self.title_color,
344 shadow_color=self.title_shadow)
346 box_img = box.image()
349 if self.box_position == 'top':
350 box_top = metr.box_top_margin
351 elif self.box_position == 'bottom':
352 box_top = metr.height - metr.box_bottom_margin - box_img.size[1]
354 box_top = (metr.height - box_img.size[1]) // 2
356 box_left = metr.bar_width + (metr.width - metr.bar_width - box_img.size[0]) // 2
358 # Draw the white box.
359 ImageDraw.Draw(img).rectangle(
360 (box_left, box_top, box_left + box_img.size[0], box_top + box_img.size[1]), fill='#fff')
361 # Paste the contents into the white box.
362 img.paste(box_img, (box_left, box_top), box_img)
365 def add_cut_lines(self, img):
369 metr = Metric(self, self.scale)
370 draw = ImageDraw.Draw(img)
371 for corner_x, corner_y in ((0, 0), (metr.width, 0), (0, metr.height), (metr.width, metr.height)):
372 dir_x = 1 if corner_x == 0 else -1
373 dir_y = 1 if corner_y == 0 else -1
374 for offset in (-1, 0, 1):
375 draw.line((corner_x, corner_y + dir_y * metr.bleed + offset,
376 corner_x + dir_x * metr.bleed * line_ratio, corner_y + dir_y * metr.bleed + offset),
377 fill='black' if offset == 0 else 'white', width=1)
378 draw.line((corner_x + dir_x * metr.bleed + offset, corner_y,
379 corner_x + dir_x * metr.bleed + offset, corner_y + dir_y * metr.bleed * line_ratio),
380 fill='black' if offset == 0 else 'white', width=1)
384 metr = Metric(self, self.scale)
385 img = Image.new('RGB', (metr.width, metr.height), self.background_color)
386 draw = ImageDraw.Draw(img)
388 draw.rectangle((0, 0, metr.bar_width, metr.height), fill=self.bar_color)
390 if self.background_img:
391 src = Image.open(self.background_img)
392 trg_size = (metr.width - metr.bar_width, metr.height)
393 if src.size[0] * trg_size[1] < src.size[1] * trg_size[0]:
396 int(round(src.size[1] * trg_size[0] / src.size[0]))
398 cut = (resized[1] - trg_size[1]) // 2
399 src = src.resize(resized, Image.ANTIALIAS)
400 src = src.crop((0, cut, src.size[0], src.size[1] - cut))
403 int(round(src.size[0] * trg_size[1] / src.size[1])),
406 cut = (resized[0] - trg_size[0]) // 2
407 src = src.resize(resized, Image.ANTIALIAS)
408 src = src.crop((cut, 0, src.size[0] - cut, src.size[1]))
410 img.paste(src, (metr.bar_width, 0))
413 img = self.add_box(img)
415 # img = self.add_cut_lines(img)
420 class WLNoBoxCover(WLCover):
421 def add_box(self, img):
425 class LogoWLCover(WLCover):
427 gradient_logo_height = 60
428 gradient_logo_margin_right = 30
429 gradient_logo_spacing = 40
430 gradient_color = '#000'
431 gradient_opacity = .6
433 'res/wl-logo-white.png',
434 'res/fnp-logo-white.png',
437 def __init__(self, book_info, *args, **kwargs):
438 super(LogoWLCover, self).__init__(book_info, *args, **kwargs)
439 self.gradient_height += self.bleed
440 self.gradient_logo_margin_right += self.bleed
442 self.additional_cover_logos = [
443 BytesIO(URLOpener().open(cover_logo_url).read())
444 for cover_logo_url in book_info.cover_logo_urls
448 img = super(LogoWLCover, self).image()
449 metr = Metric(self, self.scale)
450 gradient = Image.new('RGBA', (metr.width - metr.bar_width, metr.gradient_height), self.gradient_color)
451 gradient_mask = Image.new('L', (metr.width - metr.bar_width, metr.gradient_height))
452 draw = ImageDraw.Draw(gradient_mask)
453 for line in range(0, metr.gradient_height):
455 (0, line, metr.width - metr.bar_width, line),
456 fill=int(255 * self.gradient_opacity * line / metr.gradient_height))
457 img.paste(gradient, (metr.bar_width, metr.height - metr.gradient_height), mask=gradient_mask)
459 cursor = metr.width - metr.gradient_logo_margin_right
460 logo_top = int(metr.height - metr.gradient_height / 2 - metr.gradient_logo_height / 2 - metr.bleed / 2)
462 logos = [get_resource(logo_path) for logo_path in self.gradient_logos[::-1]]
463 logos = logos + self.additional_cover_logos
464 logos = [Image.open(logo_bytes).convert('RGBA') for logo_bytes in logos]
466 # See if logos fit into the gradient. If not, scale down accordingly.
467 space_for_logos = metr.width - metr.bar_width - 2 * metr.gradient_logo_margin_right
468 widths = [logo.size[0] * metr.gradient_logo_height / logo.size[1] for logo in logos]
469 taken_space = sum(widths) + (len(logos) - 1) * (metr.gradient_logo_spacing)
470 logo_scale = space_for_logos / taken_space if taken_space > space_for_logos else 1
471 logo_top += int(metr.gradient_logo_height * (1 - logo_scale) / 2)
473 for i, logo in enumerate(logos):
476 int(round(widths[i] * logo_scale)),
477 int(round(metr.gradient_logo_height * logo_scale))
480 cursor -= logo.size[0]
481 img.paste(logo, (cursor, logo_top), mask=logo)
482 cursor -= int(round(metr.gradient_logo_spacing * logo_scale))
487 class EbookpointCover(LogoWLCover):
488 gradient_logo_height = 58
489 gradient_logo_spacing = 25
491 'res/ebookpoint-logo-white.png',
492 'res/wl-logo-white.png',
493 'res/fnp-logo-white.png',
497 class VirtualoCover(Cover):
506 class PrestigioCover(Cover):
509 background_img = get_resource('res/cover-prestigio.png')
512 author_margin_left = 118
513 author_margin_right = 62
515 author_color = '#fff'
516 author_shadow = '#000'
517 author_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
518 author_font_size = 50
521 title_margin_left = 118
522 title_margin_right = 62
525 title_shadow = '#000'
526 title_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
529 def pretty_title(self):
530 return u"„%s”" % self.title
533 class BookotekaCover(Cover):
536 background_img = get_resource('res/cover-bookoteka.png')
539 author_margin_left = 307
540 author_margin_right = 233
541 author_lineskip = 156
542 author_color = '#d9d919'
543 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
544 author_font_size = 130
547 title_margin_left = 307
548 title_margin_right = 233
550 title_color = '#d9d919'
551 title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
552 title_font_size = 140
557 class GandalfCover(Cover):
560 background_img = get_resource('res/cover-gandalf.png')
561 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
562 author_font_size = 30
563 title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
570 class KMLUCover(LogoWLCover):
571 gradient_logo_height = 58
572 gradient_logo_spacing = 25
574 'res/kmlu-logo-white.png',
575 'res/wl-logo-white.png',
576 'res/fnp-logo-white.png',
580 class MPWCover(LogoWLCover):
581 gradient_logo_height = 58
582 gradient_logo_spacing = 25
584 'res/mpw-logo-white.png',
585 'res/wl-logo-white.png',
586 'res/fnp-logo-white.png',
590 class AtriumCover(LogoWLCover):
591 gradient_logo_height = 58
592 gradient_logo_spacing = 25
594 'res/atrium-logo.png',
595 'res/wl-logo-white.png',
596 'res/fnp-logo-white.png',
601 'default': LogoWLCover,
604 'atrium': AtriumCover,
608 def make_cover(book_info, *args, **kwargs):
609 if 'cover_class' in kwargs:
610 cover_class_name = kwargs.pop('cover_class')
612 cover_class_name = book_info.cover_class
613 cover_class = COVER_CLASSES[cover_class_name]
614 return cover_class(book_info, *args, **kwargs)