搜索
首页后端开发php教程php上传图片并压缩的实现方法_php技巧

本文实例讲解了php上传图片并压缩的实现方法,之前一篇《PHP实现图片上传并压缩》已经为大家进行了简单介绍,此次实现上传图片然后按照比例缩略图,指定缩略图的最大高度或者最大宽度,具体内容如下

实现代码:

<&#63;php 
function _UPLOADPIC($upfile, $maxsize, $updir, $newname = 'date') { 
  
 if ($newname == 'date') 
 $newname = date ( "Ymdhis" ); //使用日期做文件名 
 $name = $upfile ["name"]; 
 $type = $upfile ["type"]; 
 $size = $upfile ["size"]; 
 $tmp_name = $upfile ["tmp_name"]; 
  
 switch ($type) { 
 case 'image/pjpeg' : 
 case 'image/jpeg' : 
  $extend = ".jpg"; 
  break; 
 case 'image/gif' : 
  $extend = ".gif"; 
  break; 
 case 'image/png' : 
  $extend = ".png"; 
  break; 
 } 
 if (emptyempty ( $extend )) { 
 echo ( "警告!只能上传图片类型:GIF JPG PNG" ); 
 exit (); 
 } 
 if ($size > $maxsize) { 
 $maxpr = $maxsize / 1000; 
 echo ( "警告!上传图片大小不能超过" . $maxpr . "K!" ); 
 exit (); 
 } 
 if (move_uploaded_file ( $tmp_name, $updir . $newname . $extend )) { 
 return $updir . $newname . $extend; 
 } 
} 
 
function show_pic_scal($width, $height, $picpath) { 
 $imginfo = GetImageSize ( $picpath ); 
 $imgw = $imginfo [0]; 
 $imgh = $imginfo [1]; 
  
 $ra = number_format ( ($imgw / $imgh), 1 ); //宽高比 
 $ra2 = number_format ( ($imgh / $imgw), 1 ); //高宽比 
  
 
 if ($imgw > $width or $imgh > $height) { 
 if ($imgw > $imgh) { 
  $newWidth = $width; 
  $newHeight = round ( $newWidth / $ra ); 
  
 } elseif ($imgw < $imgh) { 
  $newHeight = $height; 
  $newWidth = round ( $newHeight / $ra2 ); 
 } else { 
  $newWidth = $width; 
  $newHeight = round ( $newWidth / $ra ); 
 } 
 } else { 
 $newHeight = $imgh; 
 $newWidth = $imgw; 
 } 
 $newsize [0] = $newWidth; 
 $newsize [1] = $newHeight; 
  
 return $newsize; 
} 
 
 
 
function getImageInfo($src) 
{ 
 return getimagesize($src); 
} 
/** 
* 创建图片,返回资源类型 
* @param string $src 图片路径 
* @return resource $im 返回资源类型 
* **/ 
function create($src) 
{ 
 $info=getImageInfo($src); 
 switch ($info[2]) 
 { 
 case 1: 
  $im=imagecreatefromgif($src); 
  break; 
 case 2: 
  $im=imagecreatefromjpeg($src); 
  break; 
 case 3: 
  $im=imagecreatefrompng($src); 
  break; 
 } 
 return $im; 
} 
/** 
* 缩略图主函数 
* @param string $src 图片路径 
* @param int $w 缩略图宽度 
* @param int $h 缩略图高度 
* @return mixed 返回缩略图路径 
* **/ 
 
function resize($src,$w,$h) 
{ 
 $temp=pathinfo($src); 
 $name=$temp["basename"];//文件名 
 $dir=$temp["dirname"];//文件所在的文件夹 
 $extension=$temp["extension"];//文件扩展名 
 $savepath="{$dir}/{$name}";//缩略图保存路径,新的文件名为*.thumb.jpg 
 
 //获取图片的基本信息 
 $info=getImageInfo($src); 
 $width=$info[0];//获取图片宽度 
 $height=$info[1];//获取图片高度 
 $per1=round($width/$height,2);//计算原图长宽比 
 $per2=round($w/$h,2);//计算缩略图长宽比 
 
 //计算缩放比例 
 if($per1>$per2||$per1==$per2) 
 { 
 //原图长宽比大于或者等于缩略图长宽比,则按照宽度优先 
 $per=$w/$width; 
 } 
 if($per1<$per2) 
 { 
 //原图长宽比小于缩略图长宽比,则按照高度优先 
 $per=$h/$height; 
 } 
 $temp_w=intval($width*$per);//计算原图缩放后的宽度 
 $temp_h=intval($height*$per);//计算原图缩放后的高度 
 $temp_img=imagecreatetruecolor($temp_w,$temp_h);//创建画布 
 $im=create($src); 
 imagecopyresampled($temp_img,$im,0,0,0,0,$temp_w,$temp_h,$width,$height); 
 if($per1>$per2) 
 { 
 imagejpeg($temp_img,$savepath, 100); 
 imagedestroy($im); 
 return addBg($savepath,$w,$h,"w"); 
 //宽度优先,在缩放之后高度不足的情况下补上背景 
 } 
 if($per1==$per2) 
 { 
 imagejpeg($temp_img,$savepath, 100); 
 imagedestroy($im); 
 return $savepath; 
 //等比缩放 
 } 
 if($per1<$per2) 
 { 
 imagejpeg($temp_img,$savepath, 100); 
 imagedestroy($im); 
 return addBg($savepath,$w,$h,"h"); 
 //高度优先,在缩放之后宽度不足的情况下补上背景 
 } 
} 
/** 
* 添加背景 
* @param string $src 图片路径 
* @param int $w 背景图像宽度 
* @param int $h 背景图像高度 
* @param String $first 决定图像最终位置的,w 宽度优先 h 高度优先 wh:等比 
* @return 返回加上背景的图片 
* **/ 
function addBg($src,$w,$h,$fisrt="w") 
{ 
 $bg=imagecreatetruecolor($w,$h); 
 $white = imagecolorallocate($bg,255,255,255); 
 imagefill($bg,0,0,$white);//填充背景 
 
 //获取目标图片信息 
 $info=getImageInfo($src); 
 $width=$info[0];//目标图片宽度 
 $height=$info[1];//目标图片高度 
 $img=create($src); 
 if($fisrt=="wh") 
 { 
 //等比缩放 
 return $src; 
 } 
 else 
 { 
 if($fisrt=="w") 
 { 
  $x=0; 
  $y=($h-$height)/2;//垂直居中 
 } 
 if($fisrt=="h") 
 { 
  $x=($w-$width)/2;//水平居中 
  $y=0; 
 } 
 imagecopymerge($bg,$img,$x,$y,0,0,$width,$height,100); 
 imagejpeg($bg,$src,100); 
 imagedestroy($bg); 
 imagedestroy($img); 
 return $src; 
 } 
 
} 
 
 
&#63;>

使用方法:

$filename=(_UPLOADPIC($_FILES["upload"],$maxsize,$updir,$newname='date')); 
 $show_pic_scal=show_pic_scal(230, 230, $filename); 
 resize($filename,$show_pic_scal[0],$show_pic_scal[1]); 

希望本文所述对大家学习php程序设计有所帮助。

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
PHP依赖注入容器:快速启动PHP依赖注入容器:快速启动May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增强codemodocultion,可验证性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依赖注入与服务定位器PHP中的依赖注入与服务定位器May 13, 2025 am 12:10 AM

选择DependencyInjection(DI)用于大型应用,ServiceLocator适合小型项目或原型。1)DI通过构造函数注入依赖,提高代码的测试性和模块化。2)ServiceLocator通过中心注册获取服务,方便但可能导致代码耦合度增加。

PHP性能优化策略。PHP性能优化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)启用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替换loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP电子邮件验证:确保正确发送电子邮件PHP电子邮件验证:确保正确发送电子邮件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化进行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

如何使PHP应用程序更快如何使PHP应用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,关注台词:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能优化清单:立即提高速度PHP性能优化清单:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,关注台词:1)启用opcodeCachingwithapCutoredUcescriptexecutiontime.2)实现databasequerycachingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandredececonnection.4 limitsclection.4.4

PHP依赖注入:提高代码可检验性PHP依赖注入:提高代码可检验性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显着提升了PHP代码的可测试性。 1)DI解耦类与具体实现,使测试和维护更灵活。 2)三种类型中,构造函数注入明确表达依赖,保持状态一致。 3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能优化:数据库查询优化PHP性能优化:数据库查询优化May 12, 2025 am 12:02 AM

databasequeryOptimizationinphpinvolVolVOLVESEVERSEVERSTRATEMIESOENHANCEPERANCE.1)SELECTONLYNLYNESSERSAYCOLUMNSTORMONTOUMTOUNSOUDSATATATATATATATATATATRANSFER.3)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。