位置:首页 > PHP > PHP功能函数 > php图片处理函数相关 >

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

字号+ 作者:micloud 来源:www.seoalphas.com 2017-09-14 08:20 浏览量:2819

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

<?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 函数


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • php图片添加文字水印 以及图片合成加水印图片

    php图片添加文字水印 以及图片合成加水印图片

    浏览次数:5746

  • PHP中data/base64数据流转图片文件输出

    PHP中data/base64数据流转图片文件输出

    浏览次数:5144

  • php获取文章中图片img标签方法

    php获取文章中图片img标签方法

    浏览次数:4971

  • PHP 拷贝图像 imagecopy 与 imagecopyresized 函数

    PHP 拷贝图像 imagecopy 与 imagecopyresized 函数

    浏览次数:2693

网友点评
评论区域