from PIL import Image, ImageDraw from io import BytesIO # Pixel position information for each area of the card image # Card CARD_SIZE = (868, 1213) # Picture PICTURE_WHITE_LT_XY = (65, 188) PICTURE_WHITE_RB_XY = (802, 925) # Title TITLE_BLEND_WHITE_LT_XY = (34, 29) TITLE_BLEND_WHITE_RB_XY = (833, 149) # Main Body of Description DESCRIPTION_BLEND_WHITELT_XY = (34, 961) DESCRIPTION_BLEND_WHITERB_XY = (833, 1185) def average_with_white(img, area): # Change alpha value x1, y1, x2, y2 = area for x in range(x1, x2): for y in range(y1, y2): r, g, b = img.getpixel((x, y)) img.putpixel((x, y), ((r + 255) // 2, (g + 255) // 2, (b + 255) // 2)) return img def create_card_frame(img_bytearray): card_img = Image.open(img_bytearray).convert('RGB') card_img = card_img.resize(CARD_SIZE) card_imgdraw = ImageDraw.Draw(card_img) # Paint White to the Picture Area card_img.paste((255, 255, 255), PICTURE_WHITE_LT_XY + PICTURE_WHITE_RB_XY) # Make translucent to the Title Area card_img = average_with_white(card_img, TITLE_BLEND_WHITE_LT_XY + TITLE_BLEND_WHITE_RB_XY) # Draw black rectangle frame to the Title Area card_imgdraw.rectangle(TITLE_BLEND_WHITE_LT_XY + TITLE_BLEND_WHITE_RB_XY, outline=(0, 0, 0), width=5) # Make translucent to the Description Area card_img = average_with_white(card_img, DESCRIPTION_BLEND_WHITELT_XY + DESCRIPTION_BLEND_WHITERB_XY) # Draw rectangle frame to the Description Area card_imgdraw.rectangle(DESCRIPTION_BLEND_WHITELT_XY + DESCRIPTION_BLEND_WHITERB_XY, outline=(0, 0, 0), width=5) # Outputting Binary Data output_img_bytearray = BytesIO() card_img.save(output_img_bytearray, "PNG", quality=95) output_img_bytearray.seek(0) # Seek to the beginning of the image, otherwise it results in empty data return output_img_bytearray if __name__ == '__main__': with open('data/cards/back/cats.png', 'rb') as f: card_frame_bytearray = BytesIO(f.read()) card_frame_bytearray = create_card_frame(card_frame_bytearray) with open('test.jpeg', 'wb') as f: f.write(card_frame_bytearray.read())