Spaces:
Running
Running
| from PIL import Image | |
| # class WatermarkApp: | |
| # def __init__(self): | |
| # pass | |
| # def process_image(self, image): | |
| # watermark = Image.open('asset/chaojihui-v2.png') | |
| # # 获取水印的等比例缩放尺寸 | |
| # wm_width, wm_height = watermark.size | |
| # import random | |
| # # target_size = random.randint(100, 300) | |
| # 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 | |
| class WatermarkApp: | |
| def __init__(self): | |
| pass | |
| def process_image(self, image): | |
| watermark = Image.open('asset/chaojihui-v2.png') | |
| # 获取水印的等比例缩放尺寸 | |
| wm_width, wm_height = watermark.size | |
| import random | |
| # target_size = random.randint(100, 300) | |
| 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) | |
| double_image = Image.new('RGBA', (image.width * 2, image.height * 2), (0, 0, 0, 0)) | |
| for y in range(0, double_image.height, new_wm_height): | |
| for x in range(0, double_image.width, new_wm_width): | |
| double_image.alpha_composite(wm, dest=(x, y)) | |
| angle = random.uniform(-180, 180) | |
| double_image = double_image.rotate(angle) | |
| print(double_image) | |
| double_image = double_image.crop((image.width//2, image.height//2, (image.width*3)//2, (image.height*3)//2)).resize(image.size, Image.Resampling.LANCZOS) | |
| print(double_image) | |
| # 确保原图是RGBA模式 | |
| if image.mode != 'RGBA': | |
| image = image.convert('RGBA') | |
| image.alpha_composite(double_image, dest=(0, 0)) | |
| return image | |
| def apply_transparency(self, watermark, alpha): | |
| """应用透明度""" | |
| matrix = watermark.split()[-1].point(lambda x: x * alpha) | |
| watermark.putalpha(matrix) | |
| return watermark | |