highlighter

Sonntag, 24. November 2024

convert to png from heif | jpg on windows using with python

  iPhoneで撮り溜めた写真を一枚ずつ画像編集ソフトで変換すると辛いのでいい加減スクリプトを導入しました, 使うものはwindows標準のPowerShellとNotepadのみです.

  C:\\Users\\foobar\\Desktop*1へ変換後のファイルを出力しやうと思いましたらば権限エラーとなりましたので適当なフォルダをデスクトップ上に作成し其処へ出力する形にしたら無事変換出来ました. 読み込みはDesktop上直からで問題なかつたのでDesktopへの書き出し権限を変更出来るなら可能かもしれません(?).

  今回は盛り込みませんでしたがpythonの実行時に引数を渡せるのでそれをsys.argvで取得する事でファイルの読み込みパスと出力先パスの指定は簡単に変更可能です.

  画像のサイズ変更処理を追加&変換処理を関数へ切り出しました. 画像サイズの縦横比が1だつた場合は考慮しておりません(サイズ変更を行わない). 後は適当に使い勝手の良いやうにすれば良いと思います(調べればグレースケールetc etc情報が沢山出てきますので画像変換で遊ぶのも良いかと思われます).

  python-pillow.org :: Pillow

  以下必要な操作概略です.

  • ScoopとPythonのインストール(Pythonをインストールするに際し今回はScoopというパッケージマネージャを選択しました)
    • Set-ExecutionPolicy RemoteSigned -scope CurrentUser
    • invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://get.scoop.sh')
    • scoop install python
    • scoop list
  • Pythonで変換する上で必要なモジュールのインストール
    • python -m pip install --upgrade pip
    • python -m pip install image
    • python -m pip install pillow
    • python -m pip install pillow_heif
  • 変換実行
    • 作成したスクリプトを変換したいHEICファイルの保存されているディレクトリに配置する
    • PowerShellのプロンプトでスクリプトを配置したディレクトリへ移動し"python foobar.py"*2と入力しエンターキー

import os
import sys
from PIL import Image
import pillow_heif

def heic_conv():
  heic_files = [f for f in os.listdir("./") if f.endswith('.HEIC') or f.endswith('.heic')]
  for heic in heic_files:
    output_file_name = os.path.splitext(heic)[0] + '.png'
    output_file_path = os.path.join(os.getcwd() + '\\output_pngs\\', output_file_name)
    output_heif_file = pillow_heif.read_heif(heic)
    image = Image.frombytes(
      output_heif_file.mode,
      output_heif_file.size,
      output_heif_file.data,
      "raw",
      output_heif_file.mode,
      output_heif_file.stride,
    )
    print(f'width:{output_heif_file.size[0]}, height:{output_heif_file.size[1]}')
    image_width  = 1600
    image_height = 1200
    if output_heif_file.size[0] > output_heif_file.size[1]:
      resized_image = image.resize((image_width, image_height))
    elif output_heif_file.size[0] < output_heif_file.size[1]:
      resized_image = image.resize((image_height, image_width))
    resized_image.save(output_file_path, 'PNG')
    print(f'converted {heic}')

if __name__ == "__main__":
  heic_conv()
import os
import sys
from PIL import Image

# jpg → png版, pillow_heicを使わない点とfrombytesの引数が若干違うだけです
def jpg_conv():
  jpg_files = [f for f in os.listdir("./") if f.endswith('.JPG') or f.endswith('.jpg')]
  for jpg in jpg_files:
    output_file_name = os.path.splitext(jpg)[0] + '.png'
    output_file_path = os.path.join(os.getcwd() + '\\outputs\\', output_file_name)
    img = Image.open(jpg)
    image = Image.frombytes(
      "RGB",
      img.size,
      img.tobytes("raw"),
      "raw",
      img.mode
    )
    print(f'width:{img.width}, height:{img.height}')
    image_width = 1600
    image_height = 1200
    if img.width > img.height:
      resized_image = image.resize((image_width, image_height))
    else:
      resized_image = image.resize((image_height, image_width))
    resized_image.save(output_file_path, 'PNG')
    print(f'converted {jpg}')

if __name__ == '__main__':
  jpg_conv()

  *1: foobarの部分はPCを使う方に因つて固有なものなので任意の名称を付けてください.
  *2: 脚注*1と同様です.