![見出し画像](https://assets.st-note.com/production/uploads/images/143696665/rectangle_large_type_2_8f005a13b9aef88b1408b348cf5e1ace.png?width=1200)
Photo by
golchiki
Python Pillowであっという間に複数のPNGをJPGへ変換
今日はPython初心者です。
今回のお題は今までは業務で複数のiPhoneで撮影したPNGファイルをMACのプレビューで書き出しでJPGに変換していました。もっと早くできる方法をPYTHONでやってみようと思いました。
今回はこのブログを書いたりコードを書くのに時間がかかりましたが
今後はこれで業務が爆速にできると思います。
VScodeにPythonと仮想環境がアクティブになっている前提です。
もしかするとGoogle ColabやJupyterのほうが早いかもしれませんが、今回はVS Codeで実装しました。
まずは仮想環境をアクティベート
source venv/bin/activate
Pillowをインストール
Pillow: Pythonの画像処理ライブラリで、画像の開閉、編集、保存が可能
pip install pillow
特定のフォルダに入った複数のPNGを1MB以下に変換
resize.pyを作成
osモジュール: Python標準ライブラリで、ファイルやディレクトリの操作を提供
import os
from PIL import Image
# 変換するディレクトリのパス
directory = "/Users/kawamotonaoki/Desktop/motorbike-ply"
# ディレクトリ内のすべてのPNGファイルを取得
png_files = [f for f in os.listdir(directory) if f.endswith('.PNG')]
# PNGファイルを順に変換
for png_file in png_files:
file_path = os.path.join(directory, png_file)
img = Image.open(file_path)
# JPGに変換
img = img.convert("RGB")
# 保存するJPGファイルのパス
jpg_file_path = os.path.join(directory, os.path.splitext(png_file)[0] + ".jpg")
# ファイルのサイズを1MB以下に調整しながら保存
quality = 85 # 初期のクオリティ設定
while True:
img.save(jpg_file_path, "JPEG", quality=quality)
# ファイルサイズをチェック
file_size = os.path.getsize(jpg_file_path)
if file_size <= 1 * 1024 * 1024: # 1MB以下
break
quality -= 5 # クオリティを下げる
print(f"Converted {png_file} to {jpg_file_path} with size {file_size / 1024:.2f} KB")
print("All PNG files have been converted to JPG and resized to be under 1MB.")
PNG→JPG一括変換できました!
(venv) U@H ~/Desktop/motorbike-ply $ python resize.py
Converted IMG_0651.PNG to /Users/kawamotonaoki/Desktop/motorbike-ply/IMG_0651.jpg with size 263.02 KB
Converted IMG_0653.PNG to /Users/kawamotonaoki/Desktop/motorbike-ply/IMG_0653.jpg with size 258.00 KB
Converted IMG_0652.PNG to /Users/kawamotonaoki/Desktop/motorbike-ply/IMG_0652.jpg with size 260.49 KB
Converted IMG_0656.PNG to /Users/kawamotonaoki/Desktop/motorbike-ply/IMG_0656.jpg with size 264.93 KB
Converted IMG_0657.PNG to /Users/kawamotonaoki/Desktop/motorbike-ply/IMG_0657.jpg with size 267.26 KB
Converted IMG_0655.PNG to /Users/kawamotonaoki/Desktop/motorbike-ply/IMG_0655.jpg with size 268.15 KB
All PNG files have been converted to JPG and resized to be under 1MB.
まとめ
業務には発生頻度によって手動でやったほうが良い仕事と自動化したほうが良い判断の分岐があると思う。
判断するためには自動化できるかどうかの知識は必要で、知識がなければ判断の分岐さえできないのでインプットとアウトプットあるのみですね!
今日も前進あるのみ。