search
HomeBackend DevelopmentPHP Tutorialphp上传图片并压缩的实现方法_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程序设计有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),