2
2

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.

Pythonで透過pngの背景色を指定しつつjpgにする

Posted at

やりたいこと

  • どこかのフォルダにあるpngを全部処理
  • 同じフォルダに出力
  • 背景色を自分で指定

コード

  • モジュールが無いって言われたら pip install pillow
png2jpg.py
from PIL import Image
import glob
import re
import os

png_list = glob.glob('<pngがあるディレクトリ>/*.png')

for pngfile in png_list:
  png = Image.open(pngfile)
  png.load() # required for png.split()
  jpgfile = pngfile.replace(".png", ".jpg")

  background = Image.new("RGB", png.size, (255, 255, 255)) # 背景色
  background.paste(png, mask=png.split()[3]) # 3 is the alpha channel

  background.save(jpgfile, 'JPEG', quality=80) # jpgの品質はよしなに
  • 実行
python png2jpg.py
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?