From 9281abf8538bf6146e383c10f8cafad54284d460 Mon Sep 17 00:00:00 2001 From: Tanner Collin Date: Sun, 12 Jul 2020 06:21:00 +0000 Subject: [PATCH] Add function to generate member card photo --- apiserver/apiserver/api/serializers.py | 3 ++ apiserver/apiserver/api/utils.py | 39 +++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/apiserver/apiserver/api/serializers.py b/apiserver/apiserver/api/serializers.py index d8df89b..27157bb 100644 --- a/apiserver/apiserver/api/serializers.py +++ b/apiserver/apiserver/api/serializers.py @@ -158,6 +158,9 @@ class MemberSerializer(serializers.ModelSerializer): instance.photo_small = small instance.photo_medium = medium instance.photo_large = large + card_photo = utils.gen_card_photo(instance) + print(card_photo) + logger.info(card_photo) return super().update(instance, validated_data) diff --git a/apiserver/apiserver/api/utils.py b/apiserver/apiserver/api/utils.py index 916b082..f87bc4d 100644 --- a/apiserver/apiserver/api/utils.py +++ b/apiserver/apiserver/api/utils.py @@ -7,7 +7,7 @@ from datetime import datetime, timedelta from rest_framework.exceptions import ValidationError from dateutil import relativedelta from uuid import uuid4 -from PIL import Image +from PIL import Image, ImageDraw, ImageFont from bleach.sanitizer import Cleaner from PyPDF2 import PdfFileWriter, PdfFileReader from reportlab.pdfgen import canvas @@ -199,6 +199,43 @@ def process_image_upload(upload): return small, medium, large +CARD_TEMPLATE_FILE = 'misc/member_card_template.jpg' +CARD_PHOTO_SIZE = 500 +CARD_PHOTO_MARGIN_TOP = 100 +CARD_PHOTO_MARGIN_SIDE = 30 + +def gen_card_photo(member): + card_template = Image.open(CARD_TEMPLATE_FILE) + + member_photo = Image.open(STATIC_FOLDER + member.photo_large) + member_photo.thumbnail([CARD_PHOTO_SIZE, CARD_PHOTO_SIZE], Image.ANTIALIAS) + + tx, ty = card_template.size + mx, my = member_photo.size + x = tx - mx - CARD_PHOTO_MARGIN_SIDE + y = CARD_PHOTO_MARGIN_TOP + card_template.paste(member_photo, (x, y)) + + draw = ImageDraw.Draw(card_template) + + font = ImageFont.truetype('DejaVuSans.ttf', 60) + dx, dy = draw.textsize(member.first_name, font=font) + x = tx - dx - CARD_PHOTO_MARGIN_SIDE + y = my + CARD_PHOTO_MARGIN_TOP + CARD_PHOTO_MARGIN_SIDE + draw.text((x, y), member.first_name, (0,0,0), font=font) + + font = ImageFont.truetype('DejaVuSans-Bold.ttf', 72) + dx, dy = draw.textsize(member.last_name, font=font) + x = tx - dx - CARD_PHOTO_MARGIN_SIDE + y = my + CARD_PHOTO_MARGIN_TOP + CARD_PHOTO_MARGIN_SIDE + 70 + draw.text((x, y), member.last_name, (0,0,0), font=font) + + file_name = str(uuid4()) + '.jpg' + card_template.save(STATIC_FOLDER + file_name, quality=95) + + return file_name + + ALLOWED_TAGS = [ 'h3', 'p',