objektify2 / edgif.py
chohj06ms's picture
Upload 6 files
9793ed6 verified
raw
history blame
2.88 kB
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, 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)
krtime = fn.get_kr_time()
shutil.copy2("output.gif", f"/data/cache/{krtime}.gif")