My studying notes for Java,Ruby,Ajax and other any interesting things.

星期二, 九月 08, 2009

php生成缩放图片程序

<?php
 
  //return a pic str
   function pic($width,$height,$picpath,$h_center=false,$w_center=false)
   {
    $org_path = $picpath;
    if(preg_match("/^\//" , $picpath))
    {
      $picpath =$_SERVER['DOCUMENT_ROOT'] . $picpath;
    }
    $imginfo=GetImageSize($picpath);
    $imgw=$imginfo[0];
    $imgh=$imginfo[1];
 
    if($width > 0 && $height==0)
    {
     if($imgw > $width)
       {
       return "<img src=\"$org_path\" width=\"{$width}\"  border='0' />"  ;
       }else
      {
       return "<img src=\"$org_path\" width=\"{$imgw}\"  border='0' />"  ;
       }
    }else if( $width == 0 && $height > 0)
    {
     if($imgh > $height)
       {
       return "<img src=\"$org_path\"  height=\"{$height}\"   border='0' />"  ;
       }else
       {
       return "<img src=\"$org_path\"  height=\"{$height}\"   border='0' />"  ;
       }
    }
 

    $ra = ($imgw/$imgh);//宽高比
    $ra2 = ($imgh/$imgw);//高宽比
    $tg_ra = $width/$height;
 
    if ($imgw > $width || $imgh > $height)
    {
      if ($ra > $tg_ra)
      {
        $newWidth=$width;
        $newHeight=round($newWidth/$ra);
      }
      elseif ($ra < $tg_ra)
      {
        $newHeight=$height;
        $newWidth=round($newHeight/$ra2);
      }
      else
      {
        $newWidth=$width;
        $newHeight=$height;
         }
    }
    else
    {
      $newHeight=$imgh;
      $newWidth=$imgw;
    }
     $newsize[0]=$newWidth;
     $newsize[1]=$newHeight;
    $return_str = "<img src=\"$org_path\" width=\"{$newsize[0]}\"  height=\"{$newsize[1]}\" border='0' />"  ;
     if($h_center ||  $w_center)
        {     
        $marg_top = 0;
     $marg_left = 0;
     if($newsize[1] < $height && $h_center)
        {
      $marg_top =round( ($height - $newsize[1] ) / 2  );
     }
     if($newsize[0] < $width && $w_center)
        {
      $marg_left =round( ($width - $newsize[0] ) / 2  );
     }
          $return_str = "<img src=\"$org_path\" width=\"{$newsize[0]}\"  height=\"{$newsize[1]}\"  style=\"margin-top:{$marg_top}px;margin-left:{$marg_left}px; \" border='0' />";
     }
 
   
    return  $return_str ;
 }
?>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>等比例缩放</title>
</head>
 
<body>
<img src="test3.jpg" width="200" hight="200">
<? $pic_src='test3.jpg'; echo pic(100,300,$pic_src,true);?>
<br>
</body>
</html>

没有评论: