这个解决方案基本与Can Berk Güder的相同,但经过花费一些时间编写和注释后,我觉得有必要发帖。
此函数创建一个缩略图,大小完全由您给出。 图像被调整大小以最佳适应缩略图的大小。 如果两个方向都不完全符合,则在缩略图中居中。 详细的注释解释了整个过程。
function thumbnail_box($img, $box_w, $box_h) {
$new = imagecreatetruecolor($box_w, $box_h);
if($new === false) {
return null;
}
$fill = imagecolorallocate($new, 200, 200, 205);
imagefill($new, 0, 0, $fill);
$hratio = $box_h / imagesy($img);
$wratio = $box_w / imagesx($img);
$ratio = min($hratio, $wratio);
if($ratio > 1.0)
$ratio = 1.0;
$sy = floor(imagesy($img) * $ratio);
$sx = floor(imagesx($img) * $ratio);
$m_y = floor(($box_h - $sy) / 2);
$m_x = floor(($box_w - $sx) / 2);
if(!imagecopyresampled($new, $img,
$m_x, $m_y, //dest x, y (margins)
0, 0, //src x, y (0,0 means top left)
$sx, $sy,//dest w, h (resample to this size (computed above)
imagesx($img), imagesy($img)) //src w, h (the full size of the original)
) {
imagedestroy($new);
return null;
}
return $new;
}
使用示例:
$i = imagecreatefromjpeg("img.jpg");
$thumb = thumbnail_box($i, 210, 150);
imagedestroy($i);
if(is_null($thumb)) {
header('HTTP/1.1 500 Internal Server Error');
exit();
}
header('Content-Type: image/jpeg');
imagejpeg($thumb);
$m_y = 0
$m_x = ?
。 - Khawer Zeshan$m_y = 0; $m_x = $box_w - $sx;
就可以了。 - gnud