planet-green.com

気の向くままに。» 雑記ブログ😬

[開発/備忘録][PHP] 複数の画像を結合した1枚のサムネイル画像を自動作成する

複数の画像を入力すると結合された1枚のサムネイル画像を作成するPHP用のライブラリです。
SNSなどでよく見かけるタイプの結合サムネイルです。
サイズは自動計算してくれます。某SNS用に作りました。
create combine thumbnail from multiple images.

System Requirements:
PHP v5.3+
ImageMagick

【実行例】

4枚の元画像を入力 / source image files



↓↓↓↓↓↓↓↓
連結して1枚のサムネイル画像を出力 / output a thumbnail  image
combine thumbnail library for php

元画像は1〜4枚に対応。

・2枚の場合は上下に並びます。 / in case of two src images
combine thumbnail library for php.(two images)

・3枚の場合は横に。 / in case of three src images
combine thumbnail library for php.(three images images)

コードと使用例。試しにGithub Gistにコードを載せてみました。

<?php
/*
* combine_thumb.php
*
* examples - http://planet-green.com/archives/446
*
* System Requirements:
* PHP v5.3+
* ImageMagick
*
* Copyright (c) 2017 tomoya kawabata.
* http://planet-green.com/
*
* Released under the MIT license
* (See copy at http://opensource.org/licenses/mit-license.php)
*/
class combine_thumb
{
static function build_combine_thumb(Array $filePaths, $size_w, $size_h , $dest_jpg_path, $quality=70)
{
$img_dest = new Imagick();
if ( !$img_dest )
{
throw new Exception("Can't create new image.");
}
$img_dest->newImage($size_w, $size_h, new ImagickPixel('rgb(200,200,200)'));
$img_cnt = count($filePaths);
switch($img_cnt)
{
case 1:
$_size_w = $size_w;
$_size_h = $size_h;
break;
case 2:
$_size_w = $size_w;
$_size_h = $size_h/2;
break;
case 3:
$_size_w = $size_w / 3;
$_size_h = $size_h;
break;
default:
case 4:
$_size_w = $size_w / 2;
$_size_h = $size_h / 2;
break;
}
$x = $y = 0;
foreach ($filePaths as $file)
{
$img_tmp = new Imagick($file);
if ( !$img_tmp )
{
throw new Exception("Can't open image file.");
}
$img_tmp->stripImage();
$img_tmp->cropthumbnailimage( round($_size_w)+1, round($_size_h)+1);
$img_dest->compositeImage( $img_tmp, imagick::COMPOSITE_DEFAULT, round($x), round($y) );
$img_tmp->clear();
$x += $_size_w;
if( $x >= $size_w )
{
$x = 0;
$y += $_size_h;
}
}
$img_dest->setImageFormat('jpeg');
$img_dest->setCompression(Imagick::COMPRESSION_JPEG);
$img_dest->setImageCompressionQuality($quality);
$img_dest->writeImage($dest_jpg_path);
$img_dest->clear();
return true;
}
}
<?php
require_once "combine_thumb.php";
$filePaths = array(
"/path/to/src/image1.jpg",
"/path/to/src/image2.jpg",
"/path/to/src/image3.jpg",
"/path/to/src/image4.jpg",
);
$dest_jpg_path = "/path/to/dest/output.jpg";
combine_thumb::build_combine_thumb($filePaths, 80, 80 , $dest_jpg_path, 70);

次へ 投稿

前へ 投稿

返信する

* 画像に書かれている英数字を入力してください。

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください

© 2025 planet-green.com

テーマの著者 Anders Norén


planet-green.com