原文如下:附本人翻译(翻译水平其差,可以忽略直接看英文)

I know, it's been a while since I last blogged. This is because a lot of things are happening in my personal life. I recently relocated to London from Finland and started a new job. Things are quite busy but I will try to post an example now and then. In the meanwhile I would like to hear about sites using Imagick, so if your project is not super secret please post an url and maybe a small explanation what you're doing with Imagick on the site. This is purely for my personal interest.

Anyway, to the point. Today's example originates from a question asked by a user. How do I thumbnail the image inside given dimensions proportionally and fill the "blank" areas with a color? Well, the answer is here :)

The code is for Imagick 2.1.0 but adapting to older versions should not be hard.

翻译如下:

我知道现在离我的博客更新有一段时间了,这主要是因为最近发生了很多事。最近我找了份新工作,使我从芬兰搬到了伦敦,工作也非常忙,所以我在这里仅仅只发一个示例。同时我很高兴听到很多网站使用了imagick,我也希望如果您的项目不是很保密的话,是否能够发个链接及少量的注释以说明您的站点是如何使用Imagek的。顺便说一声,这完全是我个人的兴趣。

OK,上重头菜。今天的例子起源于一个用户的问题,那就是如果在为一张图片按比例做缩略图的时候,怎么为留空的地方用其他颜色填充。这个例子就是我的回复。

代码是FOR ImagicK 2.1.0版本,当然要改成以前的老版本代码也不是件难事。

下面就是代码了:

<?php
/* Define width and height of the thumbnail */
/* 定义缩略图的长宽*/
$width = 100;
$height = 100;

/* Instanciate and read the image in */
/*创建一个对象,同时读回源图*/
$im = new Imagick( "test.png" );
/* Fit the image into $width x $height box
The third parameter fits the image into a "bounding box" */
/*按照比例进行缩放*/
$im->thumbnailImage( $width, $height, true );
/* 按照缩略图大小创建一个有颜色的图片 */
$canvas = new Imagick();
$canvas->newImage( $width, $height, 'pink', 'png' );
/* 取得缩图的实际大小 */
$geometry = $im->getImageGeometry();
/* 计算高度 */
$x = ( $width - $geometry['width'] ) / 2;
$y = ( $height - $geometry['height'] ) / 2;
/* 合并图片 */
$canvas->compositeImage( $im, imagick::COMPOSITE_OVER, $x, $y );
/* 输出图片*/
header( "Content-Type: image/png" );
echo $canvas;
?>

膘叔,上图片

源图:

b97200df758a3c022937df8fb60d66dc

缩图:

086d2bb302b8971e878da2f4a1e50c41