频道栏目
首页 > 资讯 > 图像编程 > 正文

图片等比例缩放后裁切

16-01-07        来源:[db:作者]  
收藏   我要投稿

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

需要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);
}
?>
相关TAG标签
上一篇:在php使用PDO类查询Mysql
下一篇:php的扩展和嵌入--php内存管理
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站