Я пишу скрипт PHP, используя расширение imagick.Я хочу, чтобы скрипт сделал снимок, загруженный пользователем, и создал из него миниатюру размером 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;
}
}