1
2

More than 3 years have passed since last update.

PythonのPillowでPNG JPG変換できるようにした

Posted at

環境

macOS Catalina 10.15.6
python 3.8.2
pillow 7.2.0

動機

ネット上にあるフリーの変換ソフトは回数制限があったり、セキュリティ面で不安があったりで不便に感じる事があリました。
そこでPythonで自作してみることにしました。

仕様

前提条件、pythonプログラムと同階層にpngsとimgsというフォルダを用意。
  pngsフォルダ...変換元の画像を入れるフォルダ
  imgsフォルダ...変換後の画像を入れるフォルダ

このプログラムを実行することで、pngsフォルダ内にあるpng画像を一括でjpgに変換してimgsフォルダに保存する。

コード

from PIL import Image
import os
import datetime

input_path = os.getcwd()
# 指定ディレクトリのファイルを取得
files = os.listdir(input_path + '/pngs')

# 取得したファイルからPNGファイルのみ取得
pngs = []
for f in files:
    if f[-4:] == '.png':
        pngs.append('pngs/' + f)

# 変数を空にする
files = None

# 出力ファイル名用に現在時刻の取得
dt_now = datetime.datetime.now().strftime('%y%m%d_%H%M%S')

# 出力ファイル名または、出力パス
output_path = 'imgs/img' + dt_now

# pngをjpgに変換する
for p in pngs:
        input_img = Image.open(p)
        output_img = input_img.convert('RGB')
        output_img.save(output_path + ".jpg",quality=40)

print("finished")

終わりに

このコードはあくまで私が使いやすいように書いたものなのでそのまま使うと不都合が生じる可能性があります。なので、参考程度にお使いください。質問、訂正箇所があればお受けいたします。

参考

Pythonの画像処理ライブラリPillow(PIL)の使い方
https://note.nkmk.me/python-pillow-basic/

容量の大きいpngファイルを、jpgファイルに変換する
https://qiita.com/hirohuntexp/items/05b7a81323dff7bdca9f

Pythonのdatetimeで日付や時間と文字列を変換(strftime, strptime)
https://note.nkmk.me/python-datetime-usage/

1
2
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
1
2