画像のDPIを計算、サイズも変更するpython

表題の件、ニーズがあったので作成しました。

下記がフルコードです。

# -*- coding: utf-8 -*-
"""
Created on Fri Sep 23 01:51:23 2022

@author: chanyoGUITAR
"""

# 参考:https://qiita.com/yoko_u/items/f0fb4b0b9bc2b1905ed1
# 参考:https://phst.hateblo.jp/entry/2021/12/15/080000
# https://daeudaeu.com/pil-aspect/

import os
from PIL import Image
import pandas as pd
import numpy as np

def keepAspectResize(im, size):
    # 参考:https://daeudaeu.com/pil-aspect/

    # サイズを幅と高さにアンパック
    width, height = size

    # 矩形の幅と画像の幅の比率を計算
    x_ratio = width / im.width

    # 矩形の高さと画像の高さの比率を計算
    y_ratio = height / im.height

    # 画像の幅と高さ両方に小さい方の比率を掛けてリサイズ後のサイズを計算
    if x_ratio < y_ratio:
        resize_size = (width, round(im.height * x_ratio))
    else:
        resize_size = (round(im.width * y_ratio), height)

    # リサイズ後の画像サイズにリサイズ
    resized_image = im.resize(resize_size)
    return resized_image

if __name__ == '__main__':
    print("Start !")

    w_num = 5.1 #印刷サイズ(幅)[cm]
        
    # 出力用のDF
    out_df = pd.DataFrame(np.arange(7).reshape(1, 7),
                  columns= ['file_name','format','height','width','H/W','dpi','ext'])
         
    n = 0           
    # カレントディレクトリの全画像をループする
    fltr_list = [filename for filename in os.listdir('./input') if not filename.startswith('.')]
    for filename in fltr_list:
        
        print(filename + 'を実施します。')
        
        if not (filename.endswith('.jpg') or filename.endswith('.jpeg')):
            out_df.loc[n,'ext'] = 'other'
            # continue #.jpg、.jpeg以外はスキップする
        else:
            out_df.loc[n,'ext'] = 'jpg'
            
        out_df.loc[n,'file_name'] = filename
        im = Image.open('./input/' + filename)
    
        if im.mode == 'RGB':
            format_chk = 'RGB'
            im = im.convert('CMYK')
            out_df.loc[n,'format'] = 'RGB'
        elif im.mode == 'CMYK':
            out_df.loc[n,'format']= 'CMYK' 
        else:
            im = im.convert('CMYK')
            out_df.loc[n,'format']= 'other' 

        out_df.loc[n,'height'] = im.height
        out_df.loc[n,'width'] = im.width
        out_df.loc[n,'H/W'] = im.height / im.width
        
        # https://noveblo.com/calculate-resolution/
        out_df.loc[n,'dpi'] = im.width / (w_num / 2.54)
        
        im_out = keepAspectResize(im, [704,842]) # 横、 縦
        
        if out_df.loc[n,'ext'] == 'other':
            basename = os.path.basename(filename) # ファイルパスからファイル名を取得
            save_filepath = basename [:-4] + '.jpg' # 保存ファイルパスを作成
        else:
            save_filepath = filename
    
        out_dpi = im_out.width / (w_num / 2.54)
        im_out.save(os.path.join('output', save_filepath) 
                    ,dpi = (out_dpi, out_dpi)
                    ,quality = 95)
        
        n = n + 1
    
    out_df.to_csv('chk.csv')

解説はまた今度。

コメント

タイトルとURLをコピーしました