LoginSignup
2
0

More than 5 years have passed since last update.

PythonでPDFのHTTPレスポンスからサムネイルを生成する ~ ImageMagickを使わない方法

Posted at

概要

pdf2image(Poppler)を使ってPDFの1ページ目をもとにサムネイルを生成するプログラムを作りました。

実行環境

  • Python 3.7.2 64bit
  • MacOS Mojave 64bit

必要ライブラリ、アプリケーション

pdf2image を使っているので、pdf2imageとPopplerをインストールする必要がある。
ただし、Popplerのインストールには、Qtが必要ですが、CUIのみのLinux環境などではQtをインストールするのに一苦労します。なので、CUIのみのLinux環境の場合は、ImageMagickを使う方法をお勧めします。

$ brew install poppler
# pip install Pillow
# pip install pdf2image

コード

from PIL import Image
from io import BytesIO
from pdf2image import convert_from_bytes

def genThumb(response, thumb_width, thumb_height):
    # 高速化するために先頭ページのみ読み込む(最終ページを1ページ目にする)
    images = convert_from_bytes(response.read(), last_page=1)

    temp = BytesIO()

    # 解像度を落とし、ファイル形式をpngに変更する
    images[0].resize((thumb_width, thumb_height)).save(temp, format="png")

    return temp.getvalue()
2
0
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
0