图片等比例缩放后裁切

对于图片有固定宽高要求的网站来说,直接的缩略图并不能解决问题,因为等比例缩放的宽度或者高度是不固定的,但是网站还是要求图片的宽高是固定的,那怎么办呢,只有一个办法,首先把图片等比例缩,缩放比根据宽度和高度哪个值大来决定,然后再从缩略图中裁切中间的图片,而这裁切出来的图片就是网站需要的固定图片,下面是代码

需要php开启GD2

 

<?php
echo thumb_dblxr('./2.png','144','94','test1.png');
// 等比例缩放
function thumb_dblxr($backimg,$width,$height,$newsfile){
list($s_w,$s_h,$exten) = getimagesize($backimg);
//等比例固定算法
//$test = $s_w / 144 > $s_h / 94 ? 144 : 94;
//echo $test;die;
if($width && ($s_w / $width) > ($s_h / $height )){
$width = ($height/$s_h)*$s_w;
}else{
$height = ($width/$s_w)*$s_h;
}
echo $width."<br />";
echo $height;die;
$new = imagecreatetruecolor($width, $height);//创建一个真色彩
//根据得到的扩展名不同不用的GD库函数处理
if($exten==1){
$old = imagecreatefromgif($backimg);
}elseif ($exten==2){
$old = imagecreatefromjpeg($backimg);
}elseif ($exten==3){
$old = imagecreatefrompng($backimg);
}
//遇到gif背景透明色的处理
$otcs = imagecolortransparent($old);
if ($otcs>=0 && $otcs < imagecolorstotal($old)){
$tran = imagecolorsforindex($old, $otcs);
print_r($tran);
$newtran = imagecolorallocate($new, $tran["red"], $tran["green"], $tran["blue"]);
imagefill($new, 0, 0, $newtran);
imagecolortransparent($new,$newtran);
}

imagecopyresampled($new, $old, 0,0,0,0,$width,$height,$s_w,$s_h);
//根据得到的扩展名不同不用的GD库函数处理
if($exten==1){
imagegif($new,$newsfile);
}elseif ($exten == 2){
imagejpeg($new,$newsfile);
}elseif ($exten ==3){
imagepng($new,$newsfile);
}
imagedestroy($new);
imagedestroy($old);
}

//图片裁剪
// $backimg = './test1.png';
list($w,$h,$exten) = getimagesize($backimg);
$x = ($w - 144) / 2;
$y = ($h - 99) / 2 ;
echo cut_thumb('./test1.png',$x,$y,'144','94','tt.png');
function cut_thumb($backimg,$cut_x,$cut_y,$cut_width,$cut_height,$newfile){
list($c_w,$c_h,$c_exten)= getimagesize($backimg);
if($c_exten==1){
$back = imagecreatefromgif($backimg);
}elseif ($c_exten==2){
$back = imagecreatefromjpeg($backimg);
}elseif($c_exten==3){
$back = imagecreatefrompng($backimg);
}
$c_new = imagecreatetruecolor($cut_width, $cut_height);
imagecopyresampled($c_new, $back, 0, 0, $cut_x, $cut_y, $cut_width, $cut_height, $cut_width, $cut_height);
if($c_exten==1){
imagegif($c_new,$newfile);
}elseif ($c_exten==2){
imagejpeg($c_new,$newfile);
}elseif($c_exten==3){
imagepng($c_new,$newfile);
}
imagedestroy($back);
imagedestroy($c_new);

}
?>

 

 

文章均属 松林's blog 原创 转载请注明转自松林's blog

本文地址 : http://www.songlin51.com/archives/820.html

posted @ 2013-06-08 14:24  独行客  阅读(1483)  评论(0编辑  收藏  举报