• 微信

PHP 实现等比压缩图片尺寸和大小实例代码

作者:Alpha时间:2017-09-14 阅读数:3626 +人阅读

在实际运用中,等比例压缩图片往往用到当上传图片较大的时候,经过处理能够较少的占用空间,而且当用户浏览页面的时候,加载速度也会比较快,提用户体验。

<?php
$im = imagecreatefromjpeg('D:phpplace.jpeg');
resizeImage($im,,,'xinde','.jpg');
function resizeImage($im,$maxwidth,$maxheight,$name,$filetype)
{
   $pic_width = imagesx($im);
   $pic_height = imagesy($im);
   echo "start-----------------" ;
   if(($maxwidth && $pic_width > $maxwidth) && ($maxheight && $pic_height > $maxheight))
   {
       if($maxwidth && $pic_width>$maxwidth)
       {
           $widthratio = $maxwidth/$pic_width;
           $resizewidth_tag = true;
       }
       if($maxheight && $pic_height>$maxheight)
       {
           $heightratio = $maxheight/$pic_height;
           $resizeheight_tag = true;
       }
       if($resizewidth_tag && $resizeheight_tag)
       {
           if($widthratio<$heightratio)
               $ratio = $widthratio;
           else
               $ratio = $heightratio;
       }
       if($resizewidth_tag && !$resizeheight_tag)
           $ratio = $widthratio;
       if($resizeheight_tag && !$resizewidth_tag)
           $ratio = $heightratio;
       $newwidth = $pic_width * $ratio;
       $newheight = $pic_height * $ratio;
       if(function_exists("imagecopyresampled"))
       {
           $newim = imagecreatetruecolor($newwidth,$newheight);
           imagecopyresampled($newim,$im,,,,,$newwidth,$newheight,$pic_width,$pic_height);
       }
       else
       {
           $newim = imagecreate($newwidth,$newheight);
           imagecopyresized($newim,$im,,,,,$newwidth,$newheight,$pic_width,$pic_height);
       }
       $name = $name.$filetype;
       imagejpeg($newim,$name);
       imagedestroy($newim);
   }
   else
   {
       $name = $name.$filetype;
       imagejpeg($im,$name);
   }
}

在上述代码中用到了imagecopyresized()函数,不懂的可以看这里:PHP 拷贝图像 imagecopy 与 imagecopyresized 函数


本站所有文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:595397166@qq.com

标签: 小程序

阿尔法

软件开发工程师#全栈工程师

{include file=foot.html}