【发布时间】:2011-07-01 09:56:39
【问题描述】:
我正在使用 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;
}
}
【问题讨论】:
-
可以在 200x128px 的画布中间画一个 128x128px 的小图像吗?
-
我对 Imagick 了解不多,但根据我对图形的了解,我认为您应该创建一个带有黑色填充的矩形并将缩略图覆盖在上面。使用 Imagick 应该不难,对吧?
-
PS: 尝试将
$IM->setImageBackgroundColor("black");放在调整大小语句之后