1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
/* ----------------------------------------------------------------------------------
* [ ImageMagickを利用したサムネール画像の生成 ] のサンプル
* ベース画像の拡張子をgif形式に変換したサムネール画像作成する内容
* --------------
* thumbnailImage($thumb_width, $thumb_height);
@thumb_width : サムネール画像の幅指定 ... nullのときは、高さの同比率で縮小
@thumb_height : サムネール画像の高さ指定 ... nullのときは、幅の同比率で縮小
*
* 2016.08.23 作成 Yoshi of CXMedia Inc.
* ---------------------------------------------------------------------------------- */
// ベース画像のパス設定
$img_base = 'img_sample/Base_image.jpg';
// ベース画像パスから出力ファイル名の設定(GIF形式)
list($base_path,$img_exit) = file2path_ext_get($img_base);
$img_out = $base_path.'_thumb.gif';
// ImageMagickのコンストラクタからインスタンスの作成
$img_obj = new Imagick( realpath($img_base) );
// サムネールサイズの編集とオブジェクト出力(参照渡し)
$thumbSize = 320;
thumbnailImageSizing($img_obj,$thumbSize);
// 指定した名前で画像の出力:(PHP5.3以降とPHP5.2の出力処理判断)
imageWrite($img_obj,$img_out);
echo "<img src=\"$img_out\" alt='変換したサムネール画像'>";
exit;
/* ------------------------------------------------------------
* Imagickによるサムネール画像サイズ編集オブジェクト出力
* @img_obj : Imagemagickのインスタンス(参照渡しで出力)
* @thumbSize : サムネールの縦横共通サイズ
* ------------------------------------------------------------ */
function thumbnailImageSizing(&$img_obj,$thumbSize){
// ベース画像の縦横サイズの取得
$basesize = $img_obj->getImagePage();
//縦横のサイズでどちらが利用されるかの縦横比率の算出
$ratio_x = $thumbSize / $basesize['width'];
$ratio_y = $thumbSize / $basesize['height'];
// 画像作成:縦横比の固定は縦横どちらかを0(null)にすると良い //
if($ratio_x < $ratio_y){
// 横サイズで作成 //
$img_obj->thumbnailImage($thumbSize, null);
} else {
// 縦サイズで作成 //
$img_obj->thumbnailImage(null, $thumbSize);
}
}
/* ---------------------------------------------------------------
* PHPバージョンにより、writeImageFile/writeImage関数の出力処理
* @img_obj : Imagemagickのインスタンス
* @img_outpath : 出力画像の画像タイプ(拡張子)つきパス
* --------------------------------------------------------------- */
function imageWrite($img_obj,$img_outpath){
// PHPバージョンにより処理を区別
$php_ver_ary = explode('.', PHP_VERSION); // PHP_VERSIONは定数
$php_version = sprintf("%d%02d",$php_ver_ary[0],$php_ver_ary[1]);
// 指定した名前で画像の出力:PHP5.3以降とPHP5.2の処理分岐
if($php_version >= '503'){
//--PHP5.3以降は、 writeImageFileで対応--
$img_obj->writeImageFile(fopen($img_outpath,'wb'));
} else {
// --PHP5.2は、OK →PHP5.3以降 writeImage()のエラー
$img_obj->writeImage($img_outpath);
}
}
/* ------------------------------------------#
* ファイル名(パス)と拡張子を分離してget
* ----------------------------------------- */
function file2path_ext_get($str){
preg_match("/(.*)\.(.+?)$/",$str,$result);
if(isset($result[2])){return array($result[1],strtolower($result[2]));}
}
?>