3
3

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 5 years have passed since last update.

pythonで画像のアスペクト比を維持したままサイズ変更して余白を埋める

Last updated at Posted at 2017-12-05

##やりたいこと
###540x700の画像を16:9の1920x1080に変更したい(比率は変えず)

  1. 1920x1080サイズ時まで拡大した際のサイズを求める
  2. 横、縦それぞれに掛ける倍率を出す
  3. 540x700と縦の700の方が大きいので700を基準に計算
  4. 1080 / 700 = 約1.5 で約1.5倍
  5. (縦のサイズ)700 x 1.5 = 1050
  6. (横のサイズ)540 x 1.5 = 810
  7. 540x700の画像は1920x1080の16:9の比率で拡大をすると810x1050となる
  8. そしたら1920x1080まで余白を黒くする

微妙な30の隙間の埋め方がわからないので、誰か教えてくれると嬉しいです。

以下コード

image_aspect.py
# -*- coding: utf-8 -*-
from PIL import Image

class image_aspect():

    def __init__(self, image_file, aspect_width, aspect_height):
        self.img = Image.open(image_file)
        self.aspect_width = aspect_width
        self.aspect_height = aspect_height
        self.result_image = None

    def change_aspect_rate(self):

        img_width = self.img.size[0]
        img_height = self.img.size[1]

        if img_width > img_height:
            rate = self.aspect_width / img_width
        else:
            rate = self.aspect_height / img_height

        rate = round(rate, 1)
        self.img = self.img.resize((int(img_width * rate), int(img_height * rate)))
        return self

    def past_background(self):
        self.result_image = Image.new("RGB", [self.aspect_width, self.aspect_height], (0, 0, 0, 255))
        self.result_image.paste(self.img, (int((self.aspect_width - self.img.size[0]) / 2), int((self.aspect_height - self.img.size[1]) / 2)))
        return self

    def save_result(self, file_name):
        self.result_image.save(file_name)

# example
if __name__ == "__main__":
    image_aspect('./test_dir/test.jpg', 1920, 1080)\
        .change_aspect_rate()\
        .past_background()\
        .save_result('result.jpg')
3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?