我在图片标签中显示图片
<img src="image.jpg" width="100" height="50" />
我用户上传的图片尺寸为100x100我希望它像上面的标签一样显示
<img src="image.jpg" width="50" height="50" />
如何实现?
ps
如果它是服务器端问题,我正在使用php。
答案 0 :(得分:2)
使用getimagesize()
获取图片大小。然后执行此操作以缩小到适合,但保持纵横比:
if ($width > $height)
{
$ratio = (float)100 / $width;
}
else
{
$ratio = (float)100 / $height;
}
$width = (int)round($width * $ratio);
$height = (int)round($height * $ratio);
答案 1 :(得分:0)
此代码适用于任何图像到maxWidth x maxHeight框,保持纵横比和填充为白色背景。
$img = new Imagick('orig.jpg');
$maxWidth = 100;
$maxHeight = 50;
$geom = $img->getImageGeometry();
$fitWidth = (($maxWidth/$geom['width'])<($maxHeight/$geom['height']))?true:false;
if($fitWidth){
$img->thumbnailImage($maxWidth,0,false);
}else{
$img->thumbnailImage(0,$maxHeight,false);
}
$canvas = new Imagick();
$canvas->newImage($maxWidth,$maxHeight,'white','jpg');
$geom = $img->getImageGeometry();
$x = ($maxWidth-$geom['width'])/2;
$y = ($maxHeight-$geom['height'])/2;
$canvas->compositeImage($img,imagick::COMPOSITE_OVER,$x,$y);
$canvas->writeImage('thumb.jpg');