Skip to content

Instantly share code, notes, and snippets.

@plexsoup
Created September 24, 2022 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plexsoup/92beea50aa2f218db3e0a45f496f18c5 to your computer and use it in GitHub Desktop.
Save plexsoup/92beea50aa2f218db3e0a45f496f18c5 to your computer and use it in GitHub Desktop.
#@title ImagePromptEmbedder - WIP
class ImagePromptEmbedder:
def __init__(self):
return
def get_footer_height(self, image_size = (0, 0), prompt_string = "", font_size = 9, thumbnail_size = (0, 0)):
footer_height = 0
line_height = font_size * 1.5
column_width = int( (image_size[0] - thumbnail_size[0]) / (0.5 * font_size) )
footer_height = int( ((len(prompt_string) / column_width) + 1 ) * line_height) + 5
footer_height = max(footer_height, thumbnail_size[1]) # leave room for the thumbnail if it's bigger than (0.0,0.0)
return footer_height
def file_exists(filepath):
from os import path
exists = True if filepath != None and filepath != '' and path.exists(filepath) else False
return exists
def get_font(self, font_name, font_size):
import glob
import os
from PIL import ImageFont
pattern = '/usr/share/fonts/truetype/**/'+font_name
for fname in glob.glob(pattern, recursive=True):
if os.path.isfile(fname):
return(ImageFont.truetype(fname, font_size))
def append_text_to_image(self, image_obj, text_to_add="", font_size=9, thumbnail_size_for_padding=(0,0)):
from os import path
from PIL import ImageOps, ImageDraw, ImageFont
text_to_add = text_to_add.replace("\n", "").replace(" ", " ").strip()
footer_size = self.get_footer_height(image_obj.size, text_to_add, font_size, (0,0))
footer_color = "#222222"
newImage = ImageOps.expand(image_obj, (0, footer_size), footer_color ) # add top and bottom border
newImage = newImage.crop((0, footer_size, image_obj.width, image_obj.height + 2*footer_size) ) # remove the top border
# add the text to the footer
draw = ImageDraw.Draw(newImage)
myFont = self.get_font("LiberationSans-Regular.ttf", font_size) # choose a font available on default google colab, so you don't have to download anything.
highlight_color = (255,255,255)
column_width = int((image_obj.width - thumbnail_size_for_padding[0]) / (0.5 * font_size)) # adjust this later with thumbnail size if you plan to paste in a thumbnail
separated_lines = [text_to_add[index : index + column_width] for index in range(0, len(text_to_add), column_width)]
draw.multiline_text((5, image_obj.height + 5), '\n'.join(separated_lines), font=myFont, fill=highlight_color)
return newImage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment