Some optimazation

This commit is contained in:
Mr Finchum 2024-12-27 21:43:57 +01:00
parent cd62dd5312
commit bc65ae99e5

View file

@ -1,5 +1,6 @@
from PIL import Image, ImageDraw, ImageFont, ImageEnhance
import piexif
import time
class ImageProcessor:
"""Functions using pillow are in here."""
@ -41,13 +42,13 @@ class ImageProcessor:
drawer = ImageDraw.Draw(image)
imagewidth, imageheight = image.size
margin = (imageheight / 100 ) * 2 # margin dynamic, 2% of image size
font_size = imagewidth / font_size_scale # Scaling the font size
try:
try: # Try loading front, if notaviable return unmodified image
font = ImageFont.truetype("OpenDyslexic3-Regular.ttf", font_size)
except:
print("Error loading font for watermark, exiting...")
exit()
print("Error loading font for watermark, please ensure font is installed...\n")
time.sleep(0.3)
return image
c, w, textwidth, textheight, = drawer.textbbox(xy = (0, 0), text = text, font = font) # Getting text size, only need the last two values
x = imagewidth - textwidth - margin
@ -56,26 +57,34 @@ class ImageProcessor:
return image
def save_image(self, image, path, file_type, jpg_quality, png_compressing, _optimize, exif_data = None):
"""Saving images. Needs improvments."""
if exif_data != None:
if file_type == "jpg":
image.save(f"{path}.{file_type.lower()}", quality = jpg_quality, optimize = _optimize, exif = piexif.dump(exif_data))
elif file_type == "png":
image.save(f"{path}.{file_type.lower()}", compress_level = png_compressing, optimize = _optimize, exif = piexif.dump(exif_data))
else:
input(f"Type: {file_type} not yet aviable, enter to continue...")
else:
if file_type == "jpg":
image.save(f"{path}.{file_type.lower()}", quality = jpg_quality, optimize = _optimize)
elif file_type == "png":
image.save(f"{path}.{file_type.lower()}", compress_level = png_compressing, optimize = _optimize)
else:
input(f"Type: {file_type} not yet aviable, enter to continue...")
def save_image(self, image, path, file_type, jpg_quality, png_compressing, optimize, exif_data = None):
# partly optimized by chatGPT
"""
Save an image to the specified path with optional EXIF data and optimization.
"""
file_type = file_type.lower()
save_params = {"optimize": optimize}
# Add file-specific parameters
if file_type == "jpg":
save_params["quality"] = jpg_quality
elif file_type == "png":
save_params["compress_level"] = png_compressing
elif file_type not in ["webp", "jpg", "png"]:
input(f"Type: {file_type} is not supported. Press Enter to continue...")
return
# Add EXIF data if available
if exif_data is not None:
save_params["exif"] = piexif.dump(exif_data)
if file_type == "webp":
print("File format webp does not support all exif features, some information might get lost...\n")
time.sleep(0.1)
try:
image.save(f"{path}.{file_type}", **save_params)
except Exception as e:
print(f"Failed to save image: {e}")
class ExifHandler:
"""Function using piexif are here."""
def __init__(self):
pass
@ -84,7 +93,7 @@ class ExifHandler:
def build_exif_dict(self, user_data, imagesize):
"""Build a piexif-compatible EXIF dictionary from user data."""
# Mostly made by ChatGPT, some adjustment by Mr Finchum
# Mostly made by ChatGPT, some adjustment
zeroth_ifd = {
piexif.ImageIFD.Make: user_data["make"],
piexif.ImageIFD.Model: user_data["model"],
@ -96,10 +105,11 @@ class ExifHandler:
piexif.ImageIFD.YResolution: (72, 1),
}
exif_ifd = {
piexif.ExifIFD.DateTimeOriginal: user_data["date_time_original"],
piexif.ExifIFD.UserComment: user_data["user_comment"],
piexif.ExifIFD.ISOSpeedRatings: int(user_data["iso"]),
piexif.ExifIFD.PixelXDimension: imagesize[0],
piexif.ExifIFD.PixelYDimension: imagesize[1],
}
if "date_time_original" in user_data:
exif_ifd[piexif.ExifIFD.DateTimeOriginal] = user_data["date_time_original"].encode("utf-8")
return {"0th": zeroth_ifd, "Exif": exif_ifd}