CoolFace
Apppublic

Candeloro/MemeGenerator

sourceHugging Facemitupdated 3y agoView on Hugging Face
0likes
app.py67 linesDownload Raw Back to root
1import streamlit as st2from PIL import Image, ImageDraw, ImageFont3import io4import base645from datetime import datetime6 7def calculate_font_size(img_width, img_height, text):8    max_font_size = int(img_width * 0.1)9    min_font_size = int(img_width * 0.02)10 11    if len(text) < 5:12        return max_font_size13    elif len(text) < 20:14        return int((max_font_size + min_font_size) / 2)15    else:16        return min_font_size17 18def generate_meme(img_path, top_text, middle_text, bottom_text):19    img = Image.open(img_path)20    draw = ImageDraw.Draw(img)21    22    font_path = "Nasa21-l23X.ttf"23    font_size_top = calculate_font_size(img.width, img.height, top_text)24    font_size_middle = calculate_font_size(img.width, img.height, middle_text)25    font_size_bottom = calculate_font_size(img.width, img.height, bottom_text)26 27    font_top = ImageFont.truetype(font_path, font_size_top)28    font_middle = ImageFont.truetype(font_path, font_size_middle)29    font_bottom = ImageFont.truetype(font_path, font_size_bottom)30 31    draw.text((10,10), top_text, font=font_top, fill="white")32    draw.text((10,img.height // 2 - font_size_middle // 2), middle_text, font=font_middle, fill="white")33    draw.text((10,img.height - 10 - font_size_bottom), bottom_text, font=font_bottom, fill="white")34 35    return img36 37def get_image_download_link(img, filename="meme.png"):38    buffered = io.BytesIO()39    img.save(buffered, format="PNG")40    img_str = base64.b64encode(buffered.getvalue()).decode()41    href = f'<a href="data:image/png;base64,{img_str}" download="{filename}">Download Image</a>'42    return href43 44st.title("Meme Generator")45 46uploaded_file = st.file_uploader("Upload an image", type=["jpg", "png"])47 48if uploaded_file is not None:49    st.image(uploaded_file, caption='Uploaded Image.', use_column_width=True)50 51    top_text = st.text_input("Enter top text")52    middle_text = st.text_input("Enter middle text")53    bottom_text = st.text_input("Enter bottom text")54 55    if st.button("Generate Meme"):56        result_img = generate_meme(uploaded_file, top_text, middle_text, bottom_text)57 58        filename = datetime.now().strftime('%Y%m%d%H%M%S') + ".png"59        st.image(result_img, caption='Generated Meme', use_column_width=True)60 61        st.markdown(get_image_download_link(result_img, filename), unsafe_allow_html=True)62 63# References64st.write("### References:")65st.write(f"- [DOI](https://doi.org/10.57967/hf/0428)")66#st.write(f"- [arXiv](https://arxiv.org/abs/1910.09700)")67