Spaces:
Running
Running
File size: 2,746 Bytes
624937a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
import edimg
import numpy as np
from PIL import Image, ImageDraw, ImageFont, ImageColor, ImageFilter, ImageSequence
import math
def find_smallest_n(x, y):
# 97n > x ์กฐ๊ฑด์ ๋ง์กฑํ๋ ์ต์ n ๊ณ์ฐ
n_for_x = math.ceil(x / 97)
# 150n > y ์กฐ๊ฑด์ ๋ง์กฑํ๋ ์ต์ n ๊ณ์ฐ
n_for_y = math.ceil(y / 150)
# ๋ ์กฐ๊ฑด์ ๋ชจ๋ ๋ง์กฑํ๋ ์ต์ n
n = max(n_for_x, n_for_y)
return n
remove_image_path = 'resource/remove_black.png' # Adjust the path according to your setup
remove_img_black = Image.open(remove_image_path).convert("RGBA")
def attach_gif(gif, overlay, chk):
# ๊ฒฐ๊ณผ ํ๋ ์๋ค์ ์ ์ฅํ ๋ฆฌ์คํธ
frames = []
durations = []
x, y = gif.size
n = find_smallest_n(x, y)
target_width = 97 * n
target_height = 150 * n
overlay = overlay.resize((target_width,target_height), Image.Resampling.LANCZOS)
if chk:
remove_img = remove_img_black.resize((target_width, target_height), Image.Resampling.BOX)
# GIF์ ๊ฐ ํ๋ ์์ ์ํํ๋ฉฐ ์ฒ๋ฆฌํฉ๋๋ค.
for frame in ImageSequence.Iterator(gif):
durations.append(frame.info['duration'])
# PNG ์ด๋ฏธ์ง๋ฅผ GIF ํ๋ ์๊ณผ ๊ฐ์ ํฌ๊ธฐ๋ก ์กฐ์ ํฉ๋๋ค.
# ์ด ๋ถ๋ถ์ ํ์์ ๋ฐ๋ผ ์กฐ์ ํ ์ ์์ต๋๋ค
resized_frame = frame.copy()
img = resized_frame
# ์๋ณธ ์ด๋ฏธ์ง์ ํฌ๊ธฐ์ ๋น์จ ๊ณ์ฐ
original_width, original_height = img.size
ratio = min(original_width / target_width, original_height / target_height)
# ์๋ก์ด ํฌ๊ธฐ ๊ณ์ฐ
new_width = int(target_width * ratio)
new_height = int(target_height * ratio)
# ์ด๋ฏธ์ง๋ฅผ ์ค์์์ ์๋ฆ
img = img.crop(((original_width - new_width) // 2,
(original_height - new_height) // 2,
(original_width + new_width) // 2,
(original_height + new_height) // 2))
# ์ต์ข
์ ์ผ๋ก ๋ชฉํ ํด์๋๋ก ๋ฆฌ์ฌ์ด์ฆ
img = img.resize((target_width, target_height), Image.Resampling.LANCZOS)
img.paste(overlay, (0, 0), overlay)
if chk:
img.paste(remove_img, (0, 0), remove_img)
frame = img.quantize(method=2)
# ๋ ์ด๋ฏธ์ง๋ฅผ ํฉ์นฉ๋๋ค.
#combined = Image.alpha_composite(frame.convert('RGBA'), overlay)
# ๊ฒฐ๊ณผ ๋ฆฌ์คํธ์ ์ถ๊ฐํฉ๋๋ค.
frames.append(img)
# ๋ชจ๋ ํ๋ ์์ ์ฒ๋ฆฌํ ํ, ์๋ก์ด GIF๋ก ์ ์ฅํฉ๋๋ค.
frames[1].save('output.gif', save_all=True, append_images=frames[1:], loop=0, duration=durations, disposal=0, optimize=True)
|