LoginSignup
12
13

More than 5 years have passed since last update.

画像を指定のサイズに変更し余白を黒くする

Last updated at Posted at 2017-03-06

手元にある画像のサイズを全て一致させたく行いました。

まず、手元にある画像を縦横比を変えずに指定のサイズ以下になるように変形します。
縦横比を維持したまま変形するため、上下または左右に指定のサイズとのズレが生まれます。そのズレは黒く塗りつぶす、ということを行いました。

Python、PILを用いて行いました。

コード

(追記)コメントにて、@shiracamus さんに補足頂きました。あわせてご確認ください!

image.py
from PIL import Image

# 縦横のサイズを指定
width =360
height = 240

# 画像の縦横を指定のサイズより小さくなるように変形
img = Image.open("hoge.jpg")
img.thumbnail((width,height),Image.ANTIALIAS)

# 黒く塗りつぶす用の背景画像を作成
bg = Image.new("RGBA",[width,height],(0,0,0,255))

# 元の画像を、背景画像のセンターに配置
bg.paste(img,(int((width-img.size[0])/2),int((height-img.size[1])/2)))

参考

下記のサイトを参考にさせていただきました。
盗用を防ぐ!Pythonを使って画像に透かしを入れる
Pythonで画像の貼り付け

最後に

ありがとうございました。

12
13
2

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
12
13