Spaces:
Running
Running
import edimg | |
import numpy as np | |
from PIL import Image, ImageDraw, ImageFont, ImageColor, ImageFilter, ImageSequence | |
import math | |
import shutil | |
import fn | |
import fns | |
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): | |
# ๊ฒฐ๊ณผ ํ๋ ์๋ค์ ์ ์ฅํ ๋ฆฌ์คํธ | |
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) | |
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) | |
krtime = fn.get_kr_time() | |
shutil.copy2("output.gif", f"/data/cache/{krtime}.gif") | |