Spaces:
Runtime error
Runtime error
# Watermarking Lab | |
# 创建人:曾逸夫 | |
# 创建时间:2022-08-08 | |
import sys | |
import gradio as gr | |
from PIL import Image, ImageDraw, ImageFont | |
from util.fonts_opt import is_fonts | |
ROOT_PATH = sys.path[0] # 根目录 | |
DESCRIPTION = '''# Watermarking Lab v0.1''' | |
def watermarking(img, text, text_size, text_font, wm_location): | |
text_size = int(text_size) | |
draw = ImageDraw.Draw(img) | |
font = ImageFont.truetype(f"./fonts/{text_font}.ttf", text_size) | |
textwidth, textheight = draw.textsize(text, font) | |
width, height = img.size | |
if wm_location == "center": | |
x = width / 2 - textwidth / 2 | |
y = height / 2 - textheight / 2 | |
elif wm_location == "bottom right": | |
x = width - textwidth - text_size | |
y = height - textheight - text_size | |
draw.text((x, y), text, font=font) | |
return img | |
def main(): | |
is_fonts(f"{ROOT_PATH}/fonts") # 检查字体文件 | |
with gr.Blocks(css='style.css') as gyd: | |
gr.Markdown(DESCRIPTION) | |
with gr.Row(): | |
with gr.Column(): | |
with gr.Row(): | |
input_img = gr.Image(image_mode="RGB", source="upload", type="pil", label="原始图片") | |
with gr.Row(): | |
wm_location = gr.Radio(choices=["center", "bottom right"], value="center", label="位置") | |
with gr.Row(): | |
wm_text = gr.Textbox(value="水印内容", label="水印内容") | |
with gr.Row(): | |
wm_textFont = gr.Dropdown(choices=["SimSun", "TimesNewRoman", "malgun"], | |
value="TimesNewRoman", | |
label="字体") | |
with gr.Row(): | |
wm_textSize = gr.Number(value=50, label="文字大小") | |
with gr.Row(): | |
btn_01 = gr.Button(value='加水印', variant="primary") | |
with gr.Column(): | |
with gr.Row(): | |
output_img = gr.Image(type="pil", label="水印图片") | |
with gr.Row(): | |
example_list = [["./img_examples/bus.jpg", "Watermarking Text", 50, "TimesNewRoman", "bottom right"], | |
["./img_examples/zidane.jpg", "水印文字", 50, "SimSun", "center"]] | |
gr.Examples(example_list, [input_img, wm_text, wm_textSize, wm_textFont, wm_location], | |
output_img, | |
watermarking, | |
cache_examples=False) | |
btn_01.click(fn=watermarking, | |
inputs=[input_img, wm_text, wm_textSize, wm_textFont, wm_location], | |
outputs=[output_img]) | |
gyd.launch(inbrowser=True) | |
if __name__ == '__main__': | |
main() | |