search
HomeBackend DevelopmentPHP Tutorial[散分]生活便利小代码,拍照后,批量递归缩放目录图片.

新入手单反一周了,今天终于找上了机会带上老婆老妈去荔枝公园拍了一天的照,回来准备上传至相册,突然发现,每张图片都有点偏大,找工具也很累,直接上网,东拼西凑了点代码.实现将指定目录的图片,按指定大小范围缩放并输出到指定目录(含递归) ,供自己以后处理相片使用. 不多废话了,附代码.

    header('Content-type:text/html; charset=utf-8');    require "lib/imgHelper.php";    $imgHelper = new imgHelper( "dir1" );    $imgHelper->setOutputDir( "dir2" );    //默认输出在1024 768 下等比缩放,需要自定义时,$imgHelper->setOutputSize(1440,900);    $imgHelper->execution();

lib 库代码.
<?php/** * 图片处理助手 */class imgHelper{    public $srcFiles;     //源文件   array    public $srcDirs;      //源目录    public $exportDir;    //输出目录    public $exportFiles;  //输出文件  array    private  $_option = array("maxWidth"=>"1024" , "maxHeight"=>"768");    function __construct($dir = '' , $option = array() )    {        if (!$dir) return;        $this->srcDirs = $dir;        $this->srcFiles = $this->traversal($dir);        $this->setOptions( $option );    }    /**     * 设置输出目录     * @param $dir     */    public function setOutputDir( $dir )    {        if( !is_dir( $dir )) { mkdir($dir , 0777 , 1);}            $this->exportDir = $dir;    }    public function execution()    {       foreach( $this->srcFiles as $key =>$val ):           $srcImg = $val;           $toFile = str_replace( $this->srcDirs , $this->exportDir , $srcImg); //todo 简便处理.           $maxWidth = $this->_option["maxWidth"];           $maxHeight = $this->_option["maxHeight"];           $this->resize($srcImg , $toFile , $maxWidth , $maxHeight );       endforeach;    }    //缩放图片.    private  function resize($srcImage,$toFile,$maxWidth = 100,$maxHeight = 100,$imgQuality=100)    {            //创建目录目录!            $pInfo = pathinfo( $toFile );            $dir = $pInfo["dirname"];  if(!is_dir( $dir) ){ mkdir($dir , 0777 , 1);}            list($width, $height, $type, $attr) = getimagesize($srcImage);            if($width < $maxWidth  || $height < $maxHeight) return ;            switch ($type) {                case 1: $img = imagecreatefromgif($srcImage); break;                case 2: $img = imagecreatefromjpeg($srcImage); break;                case 3: $img = imagecreatefrompng($srcImage); break;            }            $scale = min($maxWidth/$width, $maxHeight/$height); //求出绽放比例            if($scale < 1) {                $newWidth = floor($scale*$width);                $newHeight = floor($scale*$height);                $newImg = imagecreatetruecolor($newWidth, $newHeight);                imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);                $newName = "";                $toFile = preg_replace("/(.gif|.jpg|.jpeg|.png)/i","",$toFile);                switch($type) {                    case 1: if(imagegif($newImg, "$toFile$newName.gif", $imgQuality))                        return "$newName.gif"; break;                    case 2: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))                        return "$newName.jpg"; break;                    case 3: if(imagepng($newImg, "$toFile$newName.png", $imgQuality))                        return "$newName.png"; break;                    default: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))                        return "$newName.jpg"; break;                }                imagedestroy($newImg);            }            imagedestroy($img);            return false;    }    /**     * 设置输出的大小     * @param string $width     * @param string $height     */    public function setOutputSize( $width = "1024" , $height = "768"){        $_option = array("maxWidth"=>"$width" , "maxHeight"=>"$height");        $this->setOptions( $_option );    }    /**     * 设置可选参数     * @param $option     */    private  function setOptions( $option)    {        foreach( $option as $key =>$val):            if( isset( $option[$key]) && $option[$key] ){                $this->_option[$key] = $val;            }        endforeach;    }    /**     * 遍得到文件夹下的所有文件     */    private function traversal($path)    {        if (!$path) return array();        $files = array();        if (!is_dir($path)) return;        foreach (scandir($path) as $file)        {            if ($file != '.' && $file != '..') {                $path2 = $path . '/' . $file;                if (is_dir($path2)) {                    $temp = $this->traversal($path2);                    $files = array_merge($files, $temp);                } else {                    if ($this->isIMg($file)) {                        $files[] = $path . "/" . $file;                    }                }            }        }        return $files;    }    /**     * 判断是否是图片     * @param $file     * @return bool     */    private function isIMg($file)   {        $pInfo  = pathinfo( $file);         $extention =  $pInfo["extension"];        return  preg_match("/(jpg)|(png)|gif/i" , $extention);    }    /** * 调试数据 */    public  function debug() {$this->pr($this->srcFiles, "待处理图片数组.");          $this->pr( $this->srcDirs , "源目录");          $this->pr( $this->exportDir , "目标目录");    }    private function  pr($array, $title = 'DEBUG', $type = 'array', $width = '')  {      /*** @格式化输出 */        $title .= date("Y-m-d H:i:s");        $widthStr = "";        if ($width) $widthStr = "width:$width" . "px";        echo "<fieldset style=\"-moz-border-radius:5px 5px 5px 5px; -moz-box-shadow:0px 0px 10px rgba(00,00,00,0.45); border: 3px solid  transparent; padding:3px; margin-top:20px; \"><legend style=\"color: #069; margin:3px; $widthStr \">$title</legend>";        echo "<div style = '-moz-border-radius:10px 10px 10px 10px;font-size:14px; color:#069; border:1px solid #F0FAF9;  font-size:9pt; background:#F0FAF9; padding:5px;'>";        print("<pre class="brush:php;toolbar:false">");        if ($type == 'json') {  $array = json_decode($array);    }        print_r($array);        print("
");        echo "

";        echo  "";    }}


回复讨论(解决方案)

刚运行了一下,发现图片太多,运行时间不够,加一句 ini_set('max_execute_time',3600); 即可.

晕一个 上面的写错了,更正为 max_execution_time 

代码没收了~~很好。

回帖超过30楼,送今日偷拍美女照片一张!

... ... 
有点吗?有点嘛?有点啊?!
回帖超过30楼,送今日偷拍美女照片一张!

哈哈,类收起,....

           $maxWidth = $this->_option["maxWidth"];
           $maxHeight = $this->_option["maxHeight"];
放到循环外不是更好些?

resize 方法显得很臃肿

进来看看

这个不错,收藏一下,要用到


最近照了3k多张图片约20G图片,本以为程序写好后,就happy 的在运行转换了,谁知,当我当睡没多久,电脑遭遇老妈黑手,直接断电式关机.打开一看,只转了400张,再次运行,这400张图片将重复操作,于是折腾了一下代码,将重复去掉,并追加日志记录功能.

//在class imgHelper 内.添加如下代码.        private $copyOverWrite = true;    private $isLog = true;    /**     * 设置是否日志记录     * @param $bool     */    public function setIsLog( $bool )    {            $this->isLog = $bool;    }    /**     * 设置是否覆盖     * @param $bool     */    public function setCopyOverWrite( $bool ){        $this->copyOverWrite = $bool;    }    //记录日志.    private function log( $str ,$title = '图片助手日志' )    {        $logFile ="log/".date("Y-m-d").".log";        $pInfo = pathinfo( $logFile );        $dir = $pInfo["dirname"];  if(!is_dir( $dir) ){ mkdir($dir , 0777 , 1);}        $str =  date("H:i:s").$str . "\n";        file_put_contents($logFile, $str,FILE_APPEND);    }


//对function resize() 进行修改//追加至首行.          if( !$this->copyOverWrite && is_file($toFile)) //当设置为不覆盖,以及文件已存在时,跳过            {                 $this->log("$toFile 已存在,且系统设置为不覆盖,将做跳过处理","操作提示");                  return ;            }            $this->log( "正在努力的生成 $toFile " );//修改后 private  function resize($srcImage,$toFile,$maxWidth = 100,$maxHeight = 100,$imgQuality=100)    {            if( !$this->copyOverWrite && is_file($toFile)) //当设置为不覆盖,以及文件已存在时,跳过            {                 $this->log("$toFile 已存在,且系统设置为不覆盖,将做跳过处理","操作提示");                  return ;            }            $this->log( "正在努力的生成 $toFile " );            //创建目录目录!            $pInfo = pathinfo( $toFile );            $dir = $pInfo["dirname"];  if(!is_dir( $dir) ){ mkdir($dir , 0777 , 1);}            list($width, $height, $type, $attr) = getimagesize($srcImage);            if($width < $maxWidth  || $height < $maxHeight) return ;            switch ($type) {                case 1: $img = imagecreatefromgif($srcImage); break;                case 2: $img = imagecreatefromjpeg($srcImage); break;                case 3: $img = imagecreatefrompng($srcImage); break;            }            $scale = min($maxWidth/$width, $maxHeight/$height); //求出绽放比例//...........

好建议,写得太随手,已修改!
           $maxWidth = $this->_option["maxWidth"];
           $maxHeight = $this->_option["maxHeight"];
放到循环外不是更好些?

resize 方法显得很臃肿

    public function execution()    {        $maxWidth = $this->_option["maxWidth"];        $maxHeight = $this->_option["maxHeight"];       foreach( $this->srcFiles as $key =>$val ):           $srcImg = $val;           $toFile = str_replace( $this->srcDirs , $this->exportDir , $srcImg); //todo 简便处理.           $this->resize($srcImg , $toFile , $maxWidth , $maxHeight );       endforeach;    }

很不错~Mark学习一下~

技术流改变生活....等楼主放美女照片

代码收藏了,原来楼主是在深圳工作

来深圳两年了,有空一起出来,聊天吹水.
代码收藏了,原来楼主是在深圳工作

1.看你echo html 标签,这是第一个问题,这个程序理应适合用命令行执行,而不是web方式

2. if($width 
3.递归目录用RecursiveDirectoryIterator 会爽很多,手册(用户讨论版)上面就有很多例程,以你能写出这个类的本领,看看应该例程不难掌握

4.resize的算法可以更加简单,再想想吧

5.图片很多的话建议用ImageMagick而不是GD,效率更高

6."\n" "/"换成PHP_EOL和DIRECTORY_SEPARATOR常量吧,兼容一下win


最后的最后,大量图片还是用工具做缩放吧,专业软件效率高而且能控制输出的图片质量
但你的这个类修改后可以用在处理上传图片的后续处理,还是用处不小

resize 这个方法,直接来自互联网, 我并未关注里面的写法,这里也不愿意去较真,更多的是快速整合与实现!
1.看你echo html 标签,这是第一个问题,这个程序理应适合用命令行执行,而不是web方式

2. if($width 
3.递归目录用RecursiveDirectoryIterator 会爽很多,手册(用户讨论版)上面就有很多例程,以你能写出这个类的……

不要纠结效率啥的,前提是生活便利

imagick 核心三行代码完成缩略图,问题是你可能正好没imagick环境呢,或者安装了版本不匹配呢,这一折腾,我转换都快完成啦
$image = new Imagick("mypicture.png");
$image->thumbnailImage(200, 150, true);
$image->writeImage("thumb.png");

前面是凑字的,可完全忽略

我主要的意思是,LZ,你能否先放出图呢?

自己用更加要快,代码漂亮反而是次要的

不纠结上不了#30啊,看来我应该把6点分开6层楼……

呵呵,大家期待放照呢  

我是来看美女的

楼主快爆照

过来参合一下~

F5已碎

有分散都没人接?快点盖到30楼

速速上图

接分外加看美女照片 兄弟们雄起啊 就差两楼了

楼下的 兄弟们终于等到你了....

照片涅

代码真心不错,最重要的是服务生活的思想,太酷了!
貌似我是30楼啊!!
中奖了!

sorry,图片在家里的机器上,回家立马补上~

不是美女揍一顿

我只对相片感兴趣

人格担保,图片来自偷拍~




请问我是看中间这个美女的上面还是下面?

echo    '先别急嘛,伯虎兄,你要知道美女这种东西,跟鲜花一样,需要有绿叶来衬托才会显出她的娇媚,你再看看嘛';

美女看了,代码收下了!!哈哈

确实是美女,不过美女是不是穿个山寨衣服呀。 “never cry” 少个“y”?

出去走走,放松心情。周末程序员们都去拍照吧~

好东西,收藏了,谢谢!

先  mark,  日后再说

确实是美女,不过美女是不是穿个山寨衣服呀。 “never cry” 少个“y”?

哈哈 这个 可以有

46楼真相

F5已碎 呵呵,笑死我了。。。

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment