5
6

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.

PDFのサムネイルを作成する

Last updated at Posted at 2017-11-28

今回はImageMagickで作成しますが、今後JavaScriptのpdf.jsを使用して試してみたいと思います。
http://mozilla.github.io/pdf.js/api/draft/PDFJS.html
pdf.js版作りました。

インストール

前提:phpと一緒にphp-pearがインストール済み

# ImageMagick

yum -y install ImageMagick ImageMagick-devel

# ImageMagick for php
# printf "\n" means press Enter (Please provide the prefix of Imagemagick installation)

printf "\n" | pecl install imagick
sed -i -e '$ a \\n[PECL]\nextension=imagick.so'  ${PHPINI_PATH}

ソース

try
{
    $imagick = new Imagick();
    $result_flag1 = $imagick->readimage($file_path . '[0]');// $file_pathはPDFの場所1ページ目のみ読み込む
    $result_flag2 = $imagick->setIteratorIndex(0);// 1ページ目
    $result_flag3 = $imagick->setImageFormat('jpeg');
    $result_flag4 = $imagick->setImageBackgroundColor('#FFFFFF');// jpegで背景が黒くなる場合の対応
    $imagick = $imagick->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);// 背景レイヤー合成
    $image_info = $imagick->getImageGeometry();
    $result_flag5 = $image_info['width'] <= $image_info['height']
                    ? $imagick->resizeImage(0, 170, Imagick::FILTER_LANCZOS, 1)// 縦長 アスペクト比維持してリサイズ
                    : $imagick->resizeImage(240, 0, Imagick::FILTER_LANCZOS, 1);// 横長 アスペクト比維持してリサイズ
    $result_flag6 = $imagick->writeimage($thumbnail_path . 'thumbnail.jpg');// $thumbnail_pathは保存場所
    $imagick->clear();
}
catch (ImagickException $exception)
{
    throw new RuntimeException('サムネイル画像の作成に失敗しました。', 0, $exception);
}

if ( ! $result_flag1 || ! $result_flag2 || ! $result_flag3 || ! $result_flag4 || ! $result_flag5 || ! $result_flag6)
{
    throw new RuntimeException('サムネイル画像の作成に失敗しました。');
}

参考

http://php.net/manual/ja/imagick.readimage.php
http://php.net/manual/ja/imagick.resizeimage.php

5
6
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
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?