php+css让缩略图显示图片的中心部分

如果原始图片为长方形,让图片缩略图只截取图片中心的正方形部分显示。

分为两部分操作,以缩略图为200px的正方形为例,因缩略图访问次数较多,为节省流量,用php生成一个图片长宽最小不小于200px的保持原图片长宽比的小图:

$thumb_width = $thumb_height = 200;

// Get new dimensions
list($width, $height) = getimagesize($filename);

// If height is longer than width, height increase, width unchanged.
if ($width < $height)
{
$thumb_height = ($thumb_width / $width) * $height;
}
else
{
$thumb_width = ($thumb_height / $height) * $width;
}

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);

第二步,用CSS显示缩小后图片的中间部分:

) no-repeat 50% 50%; max-height:200px; max-width:200px;”>

如果有更好的方法,欢迎回复。

php+css让缩略图显示图片的中心部分》上有1条评论

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s