imagick 拡張機能を使用して PHP スクリプトを作成しています。スクリプトで実行したいのは、ユーザーがアップロードした画像を取得し、そこから 200x128 のサムネイルを作成することです。
それだけではありません。明らかに、すべての画像が 200x128 のアスペクト比に適合するわけではありません。したがって、スクリプトに実行させたいのは、黒い背景でギャップを埋めることです。
現在、画像のサイズは変更されていますが、黒い背景がなく、サイズが正しくありません。基本的に、画像は常に 200x128 である必要があります。サイズ変更された画像が中央に配置され、残りのコンテンツは黒で塗りつぶされます。
何か案は?
これが私のコードです:
function portfolio_image_search_resize($image) {
// Check if imagick is loaded. If not, return false.
if(!extension_loaded('imagick')) { return false; }
// Set the dimensions of the search result thumbnail
$search_thumb_width = 200;
$search_thumb_height = 128;
// Instantiate class. Then, read the image.
$IM = new Imagick();
$IM->readImage($image);
// Obtain image height and width
$image_height = $IM->getImageHeight();
$image_width = $IM->getImageWidth();
// Determine if the picture is portrait or landscape
$orientation = ($image_height > $image_width) ? 'portrait' : 'landscape';
// Set compression and file type
$IM->setImageCompression(Imagick::COMPRESSION_JPEG);
$IM->setImageCompressionQuality(100);
$IM->setResolution(72,72);
$IM->setImageFormat('jpg');
switch($orientation) {
case 'portrait':
// Since the image must maintain its aspect ratio, the rest of the image must appear as black
$IM->setImageBackgroundColor("black");
$IM->scaleImage(0, $search_thumb_height);
$filename = 'user_search_thumbnail.jpg';
// Write the image
if($IM->writeImage($filename) == true) {
return true;
}
else {
return false;
}
break;
case 'landscape':
// The aspect ratio of the image might not match the search result thumbnail (1.5625)
$IM->setImageBackgroundColor("black");
$calc_image_rsz_height = ($image_height / $image_width) * $search_thumb_width;
if($calc_image_rsz_height > $search_thumb_height) {
$IM->scaleImage(0, $search_thumb_height);
}
else {
$IM->scaleImage($search_thumb_width, 0);
}
$filename = 'user_search_thumbnail.jpg';
if($IM->writeImage($filename) == true) {
return true;
}
else {
return false;
}
break;
}
}