Home Backend Development PHP Tutorial How to operate image attributes in PHP

How to operate image attributes in PHP

Jun 09, 2018 pm 04:09 PM
php picture Batch generation thumbnail

本篇文章主要介绍php针对图片属性操作的方法,感兴趣的朋友参考下,希望对大家有所帮助。

本文实例讲述了PHP批量生成图片缩略图的方法,具体如下:

<?php
//用PHP批量生成图片缩略图
 function mkdirs($dirname,$mode=0777)
 //创建目录(目录, [模式])
 {
  if(!is_dir($dirname))
  {
   mkdirs($dirname,$mode); //如果目录不存在,递归建立
   return mkdir($dirname,$mode);
  }
  return true;
 }
 function savefile($filename,$content=&#39;&#39;)
 //保存文件(文件, [内容])
 {
  if(function_exists(file_put_contents))
  {
   file_put_contents($filename,$content);
  }
  else
  {
   $fp=fopen($filename,"wb");
   fwrite($fp,$content);
   fclose($fp);
  }
 }
 function getsuffix($filename) //获取文件名后缀
 {
  return end(explode(".",$filename));
 }
 function checksuffix($filename,$arr) //是否为允许类型(当前, 允许)
 {
  if(!is_array($arr))
  {
   $arr=explode(",",str_replace(" ","",$arr));
  }
  return in_array($filename,$arr) ? 1 : 0;
 }
 class image
 {
  var $src; //源地址
  var $newsrc; //新图路径(本地化后)
  var $allowtype=array(".gif",".jpg",".png",".jpeg"); //允许的图片类型
  var $regif=0; //是否缩略GIF, 为0不处理
  var $keep=0; //是否保留源文件(1为保留, 0为MD5)
  var $over=0; //是否可以覆盖已存在的图片,为0则不可覆盖
  var $dir; //图片源目录
  var $newdir; //处理后的目录
  function __construct($olddir=null,$newdir=null)
  {
   $this->dir=$olddir ? $olddir : "./images/temp";
   $this->newdir=$newdir ? $newdir : "./images/s";
  }
  function reNames($src)
  {
   $md5file=substr(md5($src),10,10).strrchr($src,".");
   //MD5文件名后(例如:3293okoe.gif)
   $md5file=$this->w."_".$this->h."_".$md5file;
   //处理后文件名
   return $this->newdir."/".$md5file;
   //将源图片,MD5文件名后保存到新的目录里
  }
  function Mini($src,$w,$h,$q=80)
  //生成缩略图 Mini(图片地址, 宽度, 高度, 质量)
  {
   $this->src=$src;
   $this->w=$w;
   $this->h=$h;
   if(strrchr($src,".")==".gif" && $this->regif==0)
   //是否处理GIF图
   {
    return $this->src;
   }
   if($this->keep==0) //是否保留源文件,默认不保留
   {
    $newsrc=$this->reNames($src); //改名后的文件地址
   }
   else     //保持原名
   {
    $src=str_replace("\\","/",$src);
    $newsrc=$this->newdir.strrchr($src,"/");
   }
   if(file_exists($newsrc) && $this->over==0)
   //如果已存在,直接返回地址
   {
    return $newsrc;
   }
   if(strstr($src,"http://") && !strstr($src,$_SERVER[&#39;HTTP_HOST&#39;]))
   //如果是网络文件,先保存
   {
    $src=$this->getimg($src);
   }
   $arr=getimagesize($src); //获取图片属性
   $width=$arr[0];
   $height=$arr[1];
   $type=$arr[2];
   switch($type)
   {
    case 1:  //1 = GIF,
     $im=imagecreatefromgif($src);
     break;
    case 2:  //2 = JPG
     $im=imagecreatefromjpeg($src);
     break;
    case 3:  //3 = PNG
     $im=imagecreatefrompng($src);
     break;
    default:
     return 0;
   }
   //处理缩略图
   $nim=imagecreatetruecolor($w,$h);
   $k1=round($h/$w,2);
   $k2=round($height/$width,2);
   if($k1<$k2)
   {
    $width_a=$width;
    $height_a=round($width*$k1);
    $sw=0;
    $sh=($height-$height_a)/2;
   }
   else
   {
     $width_a=$height/$k1;
     $height_a=$height;
     $sw=($width-$width_a)/2;
     $sh = 0;
   }
   //生成图片
   if(function_exists(imagecopyresampled))
   {
    imagecopyresampled($nim,$im,0,0,$sw,$sh,$w,$h,$width_a,$height_a);
   }
   else
   {
    imagecopyresized($nim,$im,0,0,$sw,$sh,$w,$h,$width_a,$height_a);
   }
   if(!is_dir($this->newdir))
   {
    mkdir($this->newdir);
   }
   switch($type)  //保存图片
   {
    case 1:
     $rs=imagegif($nim,$newsrc);
     break;
    case 2:
     $rs=imagejpeg($nim,$newsrc,$q);
     break;
    case 3:
     $rs=imagepng($nim,$newsrc);
     break;
    default:
     return 0;
   }
   return $newsrc; //返回处理后路径
  }
  function getimg($filename)
  {
   $md5file=$this->dir."/".substr(md5($filename),10,10).strrchr($filename,".");
   if(file_exists($md5file))
   {
    return $md5file;
   }
   //开始获取文件,并返回新路径
   $img=file_get_contents($filename);
   if($img)
   {
    if(!is_dir($this->dir))
    {
     mkdir($this->dir);
    }
    savefile($md5file,$img);
    return $md5file;
   }
  }
  function reImg($src,$w,$h,$q)
  //转换缩略图(文件名和结构不变)
  {
   $this->keep=1;
   return $this->Mini($src,$w,$h,$q);
   //return 生成的地址
  }
 }
 $image=new image();
 echo $image->reImg("images/zht.jpg",75,75,80);
 echo "<br/>";
 echo $image->reImg("images/m8920.jpg",75,75,80);
 echo "<br/>";
 echo $image->getimg("./images/s/zht.jpg");
?>

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

php基于Imagick实现添加水印、文字的图片功能

php中ob函数缓冲机制

php实现评委评分器的功能

The above is the detailed content of How to operate image attributes in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1589
276
go by example http middleware logging example go by example http middleware logging example Aug 03, 2025 am 11:35 AM

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

edge pdf viewer not working edge pdf viewer not working Aug 07, 2025 pm 04:36 PM

TestthePDFinanotherapptodetermineiftheissueiswiththefileorEdge.2.Enablethebuilt-inPDFviewerbyturningoff"AlwaysopenPDFfilesexternally"and"DownloadPDFfiles"inEdgesettings.3.Clearbrowsingdataincludingcookiesandcachedfilestoresolveren

Yii Developer: Mastering the Essential Technical Skills Yii Developer: Mastering the Essential Technical Skills Aug 04, 2025 pm 04:54 PM

To become a master of Yii, you need to master the following skills: 1) Understand Yii's MVC architecture, 2) Proficient in using ActiveRecordORM, 3) Effectively utilize Gii code generation tools, 4) Master Yii's verification rules, 5) Optimize database query performance, 6) Continuously pay attention to Yii ecosystem and community resources. Through the learning and practice of these skills, the development capabilities under the Yii framework can be comprehensively improved.

VS Code shortcut to focus on explorer panel VS Code shortcut to focus on explorer panel Aug 08, 2025 am 04:00 AM

In VSCode, you can quickly switch the panel and editing area through shortcut keys. To jump to the left Explorer panel, use Ctrl Shift E (Windows/Linux) or Cmd Shift E (Mac); return to the editing area to use Ctrl ` or Esc or Ctrl 1~9. Compared to mouse operation, keyboard shortcuts are more efficient and do not interrupt the encoding rhythm. Other tips include: Ctrl KCtrl E Focus Search Box, F2 Rename File, Delete File, Enter Open File, Arrow Key Expand/Collapse Folder.

Using HTML `input` Types for User Data Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

go by example running a subprocess go by example running a subprocess Aug 06, 2025 am 09:05 AM

Run the child process using the os/exec package, create the command through exec.Command but not execute it immediately; 2. Run the command with .Output() and catch stdout. If the exit code is non-zero, return exec.ExitError; 3. Use .Start() to start the process without blocking, combine with .StdoutPipe() to stream output in real time; 4. Enter data into the process through .StdinPipe(), and after writing, you need to close the pipeline and call .Wait() to wait for the end; 5. Exec.ExitError must be processed to get the exit code and stderr of the failed command to avoid zombie processes.

Fixed: Windows Update Failed to Install Fixed: Windows Update Failed to Install Aug 08, 2025 pm 04:16 PM

RuntheWindowsUpdateTroubleshooterviaSettings>Update&Security>Troubleshoottoautomaticallyfixcommonissues.2.ResetWindowsUpdatecomponentsbystoppingrelatedservices,renamingtheSoftwareDistributionandCatroot2folders,thenrestartingtheservicestocle

Mastering Flow Control Within foreach Using break, continue, and goto Mastering Flow Control Within foreach Using break, continue, and goto Aug 06, 2025 pm 02:14 PM

breakexitstheloopimmediatelyafterfindingatarget,idealforstoppingatthefirstmatch.2.continueskipsthecurrentiteration,usefulforfilteringitemsliketemporaryfiles.3.gotojumpstoalabeledstatement,acceptableinrarecaseslikecleanuporerrorhandlingbutshouldbeused

See all articles