ブログ
ノート

Squoosh とカスタムスクリプトを使用した画像圧縮

Squoosh

https://squoosh.app

画像圧縮 Gradio Web UI

Pillow(PIL)と Gradio を使用した画像の一括圧縮。

コード

github.com/Isle-of-Chaos/image-process-webui

単一画像の処理:

def convert_to_optimized_jpeg(self, input_path, output_path):

    img = Image.open(input_path)

    if self.config['is_resize']:
        img = self.resize_image(img, self.config['max_width'], self.config['max_height'])

    fill_color = (0, 0, 0)
    if input_path.endswith('.png'):
        img = self.png_add_background(img, fill_color)

    img.save(
        output_path,
        'jpeg',
        quality=self.config['quality'],
        optimize=True,
    )

    img.close()

画像のリサイズ:

def resize_image(self, img, max_width, max_height):

    # 比率の計算
    width, height = img.size
    ratio = min(max_width / width, max_height / height)

    # 画像のリサイズ
    if ratio < 1:
        img = img.resize((int(width * ratio), int(height * ratio)), Image.LANCZOS)

    print(img.size)
    return img

マルチスレッド並列処理:

progress((0, len(images_inout)), desc="Starting")
with concurrent.futures.ThreadPoolExecutor() as executor:
    futures = [executor.submit(self.convert_to_optimized_jpeg, source, target) for [source, target] in
               images_inout]
    for _ in concurrent.futures.as_completed(futures):
        completed = completed + 1
        progress((completed, len(futures)), desc=f"Processing")

効果

シェア