Spaces:
Running
Running
import os | |
import oss2 | |
from PIL import Image | |
import gradio as gr | |
import numpy as np | |
from io import BytesIO | |
class WatermarkApp: | |
def __init__(self): | |
pass | |
def process_image(self, image): | |
watermark = Image.open('asset/chaojihui-v2.png') | |
# 获取水印的等比例缩放尺寸 | |
wm_width, wm_height = watermark.size | |
target_size = 100 | |
alpha = 0.3 | |
if wm_width > wm_height: | |
new_wm_width = target_size | |
new_wm_height = int((wm_height / wm_width) * target_size) | |
else: | |
new_wm_height = target_size | |
new_wm_width = int((wm_width / wm_height) * target_size) | |
wm = watermark.resize((new_wm_width, new_wm_height), Image.Resampling.LANCZOS) | |
# 处理透明度 | |
if alpha < 1.0: | |
wm = self.apply_transparency(wm, alpha) | |
# 确保原图是RGBA模式 | |
if image.mode != 'RGBA': | |
image = image.convert('RGBA') | |
# 在整个图片上铺满水印 | |
for y in range(0, image.height, new_wm_height): | |
for x in range(0, image.width, new_wm_width): | |
image.alpha_composite(wm, dest=(x, y)) | |
return image | |
def apply_transparency(self, watermark, alpha): | |
"""应用透明度""" | |
matrix = watermark.split()[-1].point(lambda x: x * alpha) | |
watermark.putalpha(matrix) | |
return watermark | |