0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

画像のファイルサイズが大きすぎたのでavif変換とリサイズしてちっさくしてみた

Posted at

先日新卒開発研修が終了した24卒エンジニアです。
開発研修の際に使用した画像ファイルサイズ縮小のためのコードを置いときます。

余談

コードは研修中以下のようなモチベーションがあったため、片手間に書いたやつです。

  • アプリ内に表示する画像をAPIレスポンスに含まれるバイナリデータからフロントエンド側でconvertし表示する仕様だった
  • 画像ファイルが1枚3000px*4000px(3.5MB)くらいあり明らかにサイズが大きすぎた
  • 120枚ほどあり手作業でやるのは馬鹿らしかった
  • 予めファイルサイズを小さくする必要があった

使用したライブラリ

pip install pillow

コード

repo: https://github.com/yk-mt12/convert-resize-image-avif

今回は横幅500pxでアスペクト比を固定し、.avif形式に変換しています。

import os
from PIL import Image
import pillow_avif

dir_name = 'original'
new_dir_name = 'convert'

files = os.listdir(dir_name)
new_width = 500 # リサイズ後の幅

for file in files:
    file_name = os.path.splitext(os.path.basename(file))[0]
    img = Image.open(os.path.join(dir_name, file))
    width, height = img.size

    # アスペクト比を固定してリサイズ
    new_height = int((new_width / width) * height)
    img_resize = img.resize((new_width, new_height), resample=Image.LANCZOS)
    image = img_resize.convert("RGB")
    img_resize.save(os.path.join(new_dir_name, file_name + ".avif"), format="avif")

before&after

以下のように3.3MBあったファイルサイズが、16KBまで小さくできています。

before

# ls -lh original/sample.jpg 
3.3MB original/sample.jpg

after

# ls -lh convert/sample.avif 
16KB convert/sample.avif
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?