58 lines
2.8 KiB
Python
58 lines
2.8 KiB
Python
import subprocess
|
|
from PIL import Image
|
|
import os
|
|
|
|
EXTENSIONS_IMG = ('jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp')
|
|
EXTENSIONS_VID = ('mp4', 'webm')
|
|
VALID_EXTENSIONS = EXTENSIONS_IMG + EXTENSIONS_VID
|
|
|
|
def check_ffmpeg():
|
|
try:
|
|
if os.name == 'nt': creationflags = subprocess.CREATE_NO_WINDOW
|
|
else: creationflags = 0
|
|
subprocess.run(["ffmpeg", "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, creationflags=creationflags)
|
|
return True
|
|
except (FileNotFoundError, subprocess.CalledProcessError):
|
|
return False
|
|
|
|
def video_gen(input_path_file, output_path_file, TARGET_MIN_SIZE):
|
|
vf_scale = f"scale='if(gt(iw,ih),-1,{TARGET_MIN_SIZE})':'if(gt(iw,ih),{TARGET_MIN_SIZE},-1)'"
|
|
cmd = ["ffmpeg", "-y", "-i", input_path_file, "-ss", "00:00:00", "-vframes", "1", "-vf", vf_scale, "-q:v", "2", output_path_file]
|
|
if os.name == 'nt': creationflags = subprocess.CREATE_NO_WINDOW
|
|
else: creationflags = 0
|
|
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=creationflags)
|
|
if result.returncode != 0:
|
|
raise Exception(f"FFmpeg error: {result.stderr.decode('utf-8', errors='ignore')}")
|
|
|
|
def image_and_gif_gen(input_path_file, output_path_file, TARGET_MIN_SIZE):
|
|
with Image.open(input_path_file) as img:
|
|
img_rgba = img.convert("RGBA")
|
|
background = Image.new("RGB", img_rgba.size, (255, 255, 255))
|
|
background.paste(img_rgba, mask=img_rgba)
|
|
final_img = background
|
|
width, height = final_img.size
|
|
if width <= TARGET_MIN_SIZE and height <= TARGET_MIN_SIZE:
|
|
final_img.save(output_path_file, "JPEG", quality=90)
|
|
else:
|
|
if width < height:
|
|
new_width = TARGET_MIN_SIZE
|
|
new_height = int(TARGET_MIN_SIZE * (height / width))
|
|
else:
|
|
new_height = TARGET_MIN_SIZE
|
|
new_width = int(TARGET_MIN_SIZE * (width / height))
|
|
resized_img = final_img.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
|
resized_img.save(output_path_file, "JPEG", quality=85)
|
|
|
|
def generate_thumb(input_path_file, THUMB_FOLDER, TARGET_MIN_SIZE):
|
|
ext_file = input_path_file.split(".")[-1]
|
|
if ext_file not in VALID_EXTENSIONS:
|
|
return {"status":False, "message":"Расширение не поддерживаеться!"}
|
|
thumb_filename = f"{os.path.basename(input_path_file).split(".")[-2]}.jpg"
|
|
output_path_file = os.path.join(THUMB_FOLDER, thumb_filename)
|
|
if ext_file in EXTENSIONS_IMG:
|
|
image_and_gif_gen(input_path_file, output_path_file, TARGET_MIN_SIZE)
|
|
return {"status":True}
|
|
else:
|
|
if not check_ffmpeg(): return {"status":False, "message":"ffmpeg не установлен!"}
|
|
video_gen(input_path_file, output_path_file, TARGET_MIN_SIZE)
|
|
return {"status":True} |