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
75 line_width = self.draw.textsize(line, font=font)[0]
76 line = line.strip() + ' '
78 pos_x = (self.max_width - line_width) // 2
81 self.shadow_draw.text(
82 (pos_x + self.SHADOW_X, self.height + self.SHADOW_Y),
83 line, font=font, fill=shadow_color
86 self.draw.text((pos_x, self.height), line, font=font, fill=color)
87 self.height += line_height
89 text = text[len(line):]
92 """Creates the actual Image object."""
93 image = Image.new('RGBA', (self.max_width,
94 self.height + self.padding_y))
96 shadow = self.shadow_img.filter(ImageFilter.BLUR)
97 image.paste(shadow, (0, 0), shadow)
98 image.paste(self.img, (0, 0), self.img)
100 image.paste(self.img, (0, 0))
105 """Abstract base class for cover images generator."""
108 background_color = '#fff'
109 background_img = None
112 author_margin_left = 20
113 author_margin_right = 20
115 author_color = '#000'
117 author_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
118 author_font_size = 30
121 title_margin_left = 20
122 title_margin_right = 20
126 title_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
131 uses_dc_cover = False
143 'JPEG': 'image/jpeg',
147 def __init__(self, book_info, format=None, width=None, height=None):
148 self.authors = [auth.readable() for auth in book_info.authors]
149 self.title = book_info.title
150 if format is not None:
153 self.height = int(round(height * self.width / width))
154 scale = max(float(width or 0) / self.width,
155 float(height or 0) / self.height)
159 self.scale_after = scale
161 def pretty_authors(self):
162 """Allows for decorating authors' names."""
163 return [self.authors]
165 def pretty_title(self):
166 """Allows for decorating title."""
170 metr = Metric(self, self.scale)
171 img = Image.new('RGB', (metr.width, metr.height),
172 self.background_color)
174 if self.background_img:
175 background = Image.open(self.background_img)
176 img.paste(background, None, background)
181 logo = Image.open(get_resource('res/wl-logo.png'))
184 int(round(logo.size[1] * metr.logo_width / logo.size[0]))
187 (metr.width - metr.logo_width) // 2,
188 img.size[1] - logo.size[1] - metr.logo_bottom
191 top = metr.author_top
193 metr.width - metr.author_margin_left - metr.author_margin_right,
197 author_font = ImageFont.truetype(
198 self.author_font_ttf, metr.author_font_size,
199 layout_engine=ImageFont.LAYOUT_BASIC)
200 for pa in self.pretty_authors():
201 tbox.text(pa, self.author_color, author_font, metr.author_lineskip,
203 text_img = tbox.image()
204 img.paste(text_img, (metr.author_margin_left, top), text_img)
206 top += text_img.size[1] + metr.title_top
208 metr.width - metr.title_margin_left - metr.title_margin_right,
211 title_font = ImageFont.truetype(
212 self.title_font_ttf, metr.title_font_size,
213 layout_engine=ImageFont.LAYOUT_BASIC)
214 tbox.text(self.pretty_title(), self.title_color, title_font,
215 metr.title_lineskip, self.title_shadow)
216 text_img = tbox.image()
217 img.paste(text_img, (metr.title_margin_left, top), text_img)
221 def final_image(self):
223 if self.scale_after != 1:
225 int(round(img.size[0] * self.scale_after)),
226 int(round(img.size[1] * self.scale_after))),
231 return self.mime_types[self.format]
234 return self.exts[self.format]
236 def save(self, *args, **kwargs):
238 'format': self.format,
241 default_kwargs.update(kwargs)
242 return self.final_image().save(*args, **default_kwargs)
244 def output_file(self, *args, **kwargs):
246 self.save(imgstr, *args, **kwargs)
247 return OutputFile.from_bytes(imgstr.getvalue())
250 class WLCover(Cover):
251 """Wolne Lektury cover without logos."""
255 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
256 author_font_size = 20
258 title_font_ttf = get_resource('fonts/DejaVuSerif-Bold.ttf')
261 title_box_width = 350
264 box_bottom_margin = 100
277 box_position = 'middle'
278 background_color = '#444'
279 author_color = '#444'
280 background_img = get_resource('res/cover.png')
284 u'Starożytność': '#9e3610',
285 u'Średniowiecze': '#564c09',
286 u'Renesans': '#8ca629',
288 u'Oświecenie': '#f2802e',
289 u'Romantyzm': '#db4b16',
290 u'Pozytywizm': '#961060',
291 u'Modernizm': '#7784e0',
292 u'Dwudziestolecie międzywojenne': '#3044cf',
293 u'Współczesność': '#06393d',
296 kind_box_position = {
301 def __init__(self, book_info, format=None, width=None, height=None,
303 super(WLCover, self).__init__(book_info, format=format, width=width,
306 self.box_position = book_info.cover_box_position or \
307 self.kind_box_position.get(book_info.kind, self.box_position)
309 if book_info.cover_bar_color == 'none':
312 self.bar_color = book_info.cover_bar_color or \
313 self.epoch_colors.get(book_info.epoch, self.bar_color)
315 self.title_color = self.epoch_colors.get(book_info.epoch,
319 self.box_top_margin += bleed
320 self.box_bottom_margin += bleed
321 self.bar_width += bleed
323 if book_info.cover_url:
324 url = book_info.cover_url
327 bg_src = URLOpener().open(url)
328 self.background_img = BytesIO(bg_src.read())
331 def pretty_authors(self):
332 return [a.upper() for a in self.authors]
334 def add_box(self, img):
335 if self.box_position == 'none':
338 metr = Metric(self, self.scale)
341 box = TextBox(metr.title_box_width, metr.height,
342 padding_y=metr.box_padding_y)
343 author_font = ImageFont.truetype(
344 self.author_font_ttf, metr.author_font_size,
345 layout_engine=ImageFont.LAYOUT_BASIC)
346 for pa in self.pretty_authors():
347 box.text(pa, font=author_font, line_height=metr.author_lineskip,
348 color=self.author_color, shadow_color=self.author_shadow)
350 box.skip(metr.box_above_line)
352 (metr.box_line_left, box.height, metr.box_line_right, box.height),
353 fill=self.author_color, width=metr.box_line_width
355 box.skip(metr.box_below_line)
358 title_font = ImageFont.truetype(
359 self.title_font_ttf, metr.title_font_size,
360 layout_engine=ImageFont.LAYOUT_BASIC)
361 box.text(self.pretty_title(),
362 line_height=metr.title_lineskip,
364 color=self.title_color,
365 shadow_color=self.title_shadow)
367 box_img = box.image()
370 if self.box_position == 'bottom' or box_img.size[1] + metr.box_top_margin + metr.box_bottom_margin > metr.height:
371 box_top = metr.height - metr.box_bottom_margin - box_img.size[1]
372 elif self.box_position == 'top':
373 box_top = metr.box_top_margin
375 box_top = (metr.height - box_img.size[1]) // 2
377 box_left = metr.bar_width + (
378 metr.width - metr.bar_width - box_img.size[0]
381 # Draw the white box.
382 ImageDraw.Draw(img).rectangle(
386 box_left + box_img.size[0],
387 box_top + box_img.size[1]
391 # Paste the contents into the white box.
392 img.paste(box_img, (box_left, box_top), box_img)
395 def add_cut_lines(self, img):
399 metr = Metric(self, self.scale)
400 draw = ImageDraw.Draw(img)
401 for corner_x, corner_y in (
402 (0, 0), (metr.width, 0),
403 (0, metr.height), (metr.width, metr.height)
405 dir_x = 1 if corner_x == 0 else -1
406 dir_y = 1 if corner_y == 0 else -1
407 for offset in (-1, 0, 1):
411 corner_y + dir_y * metr.bleed + offset,
412 corner_x + dir_x * metr.bleed * line_ratio,
413 corner_y + dir_y * metr.bleed + offset
415 fill='black' if offset == 0 else 'white',
420 corner_x + dir_x * metr.bleed + offset,
422 corner_x + dir_x * metr.bleed + offset,
423 corner_y + dir_y * metr.bleed * line_ratio
425 fill='black' if offset == 0 else 'white',
431 metr = Metric(self, self.scale)
432 img = Image.new('RGB', (metr.width, metr.height),
433 self.background_color)
434 draw = ImageDraw.Draw(img)
436 draw.rectangle((0, 0, metr.bar_width, metr.height),
439 if self.background_img:
440 src = Image.open(self.background_img)
441 trg_size = (metr.width - metr.bar_width, metr.height)
442 if src.size[0] * trg_size[1] < src.size[1] * trg_size[0]:
445 int(round(src.size[1] * trg_size[0] / src.size[0]))
447 cut = (resized[1] - trg_size[1]) // 2
448 src = src.resize(resized, Image.ANTIALIAS)
449 src = src.crop((0, cut, src.size[0], src.size[1] - cut))
452 int(round(src.size[0] * trg_size[1] / src.size[1])),
455 cut = (resized[0] - trg_size[0]) // 2
456 src = src.resize(resized, Image.ANTIALIAS)
457 src = src.crop((cut, 0, src.size[0] - cut, src.size[1]))
459 img.paste(src, (metr.bar_width, 0))
462 img = self.add_box(img)
464 # img = self.add_cut_lines(img)
469 class WLNoBoxCover(WLCover):
470 def add_box(self, img):
474 class LogoWLCover(WLCover):
476 gradient_logo_height = 60
477 gradient_logo_max_width = 1000
478 gradient_logo_margin_right = 30
479 gradient_logo_spacing = 40
480 gradient_color = '#000'
481 gradient_opacity = .6
483 'res/wl-logo-white.png',
484 'res/fnp-logo-white.png',
487 annotation_height = 10
489 def __init__(self, book_info, *args, **kwargs):
490 super(LogoWLCover, self).__init__(book_info, *args, **kwargs)
491 self.gradient_height += self.bleed
492 self.gradient_logo_margin_right += self.bleed
494 self.additional_cover_logos = [
495 BytesIO(URLOpener().open(cover_logo_url).read())
496 for cover_logo_url in book_info.cover_logo_urls
500 img = super(LogoWLCover, self).image()
501 metr = Metric(self, self.scale)
502 gradient = Image.new(
504 (metr.width - metr.bar_width, metr.gradient_height),
507 gradient_mask = Image.new(
509 (metr.width - metr.bar_width, metr.gradient_height)
511 draw = ImageDraw.Draw(gradient_mask)
512 for line in range(0, metr.gradient_height):
514 (0, line, metr.width - metr.bar_width, line),
516 255 * self.gradient_opacity * line / metr.gradient_height
520 (metr.bar_width, metr.height - metr.gradient_height),
523 cursor = metr.width - metr.gradient_logo_margin_right
526 - metr.gradient_height / 2
527 - metr.gradient_logo_height / 2 - metr.bleed / 2
531 get_resource(logo_path)
532 for logo_path in self.gradient_logos[::-1]
534 logos = logos + self.additional_cover_logos
536 Image.open(logo_bytes).convert('RGBA')
537 for logo_bytes in logos
540 # See if logos fit into the gradient. If not, scale down accordingly.
544 - 2 * metr.gradient_logo_margin_right
548 metr.gradient_logo_max_width,
549 logo.size[0] * metr.gradient_logo_height / logo.size[1]
554 + (len(logos) - 1) * (metr.gradient_logo_spacing)
557 space_for_logos / taken_space
558 if taken_space > space_for_logos else 1
560 logo_top += int(metr.gradient_logo_height * (1 - logo_scale) / 2)
562 for i, logo in enumerate(logos):
565 int(round(widths[i] * logo_scale)),
567 logo.size[1] * widths[i] / logo.size[0] * logo_scale
571 cursor -= logo.size[0]
576 int(round(logo_top + (metr.gradient_logo_height - logo.size[1]) * logo_scale / 2))
580 cursor -= int(round(metr.gradient_logo_spacing * logo_scale))
583 img2 = Image.new('RGBA', (metr.height, metr.height), color=None)
584 draw = ImageDraw.Draw(img2)
585 author_font = ImageFont.truetype(
586 self.author_font_ttf, metr.annotation_height,
587 layout_engine=ImageFont.LAYOUT_BASIC)
588 draw.text((self.annotation_height, self.annotation_height), self.annotation, font=author_font, fill='#FFFFFF')
590 img2 = img2.rotate(90)
593 img.alpha_composite(img2, (0, 0))
594 img = img.convert('RGB')
599 class EbookpointCover(LogoWLCover):
600 gradient_logo_height = 58
601 gradient_logo_spacing = 25
603 'res/ebookpoint-logo-white.png',
604 'res/wl-logo-white.png',
605 'res/fnp-logo-white.png',
609 class VirtualoCover(Cover):
618 class PrestigioCover(Cover):
621 background_img = get_resource('res/cover-prestigio.png')
624 author_margin_left = 118
625 author_margin_right = 62
627 author_color = '#fff'
628 author_shadow = '#000'
629 author_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
630 author_font_size = 50
633 title_margin_left = 118
634 title_margin_right = 62
637 title_shadow = '#000'
638 title_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
641 def pretty_title(self):
642 return u"„%s”" % self.title
645 class BookotekaCover(Cover):
648 background_img = get_resource('res/cover-bookoteka.png')
651 author_margin_left = 307
652 author_margin_right = 233
653 author_lineskip = 156
654 author_color = '#d9d919'
655 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
656 author_font_size = 130
659 title_margin_left = 307
660 title_margin_right = 233
662 title_color = '#d9d919'
663 title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
664 title_font_size = 140
669 class GandalfCover(Cover):
672 background_img = get_resource('res/cover-gandalf.png')
673 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
674 author_font_size = 30
675 title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
682 class KMLUCover(LogoWLCover):
683 gradient_logo_height = 58
684 gradient_logo_spacing = 25
686 'res/kmlu-logo-white.png',
687 'res/wl-logo-white.png',
688 'res/fnp-logo-white.png',
692 class MPWCover(LogoWLCover):
693 gradient_logo_height = 58
694 gradient_logo_spacing = 25
696 'res/mpw-logo-white.png',
697 'res/wl-logo-white.png',
698 'res/fnp-logo-white.png',
702 class AtriumCover(LogoWLCover):
703 gradient_logo_height = 58
704 gradient_logo_spacing = 25
706 'res/atrium-logo.png',
707 'res/wl-logo-white.png',
708 'res/fnp-logo-white.png',
712 class BNCover(LogoWLCover):
714 'res/dofinansowano.png',
717 'res/wl-logo-white.png',
719 # annotation = 'Zadanie „Udostępnienie publikacji w formatach cyfrowych” w ramach Narodowego Programu Rozwoju Czytelnictwa. Dofinansowano ze środków Ministra Kultury, Dziedzictwa Narodowego i Sportu.'
723 'default': LogoWLCover,
726 'atrium': AtriumCover,
731 def make_cover(book_info, *args, **kwargs):
732 if 'cover_class' in kwargs:
733 cover_class_name = kwargs.pop('cover_class')
735 cover_class_name = book_info.cover_class
736 cover_class = COVER_CLASSES[cover_class_name]
737 return cover_class(book_info, *args, **kwargs)