Life convenience small code, after taking pictures, batch recursively zoom catalog pictures.

Source: Internet
Author: User
Tags create directory imagejpeg
The new SLR for a week, and today finally found a chance to take the wife of the mother to the Litchi Park took a day's photo, back ready to upload to the album, suddenly found that each picture is a bit large, find tools are also very tired, direct Internet, patchwork Point code. Implements a picture of the specified directory, scaled by the specified size range and output to the specified directory (with recursion) for later processing of the photo. No more nonsense, attached code.
    Header (' content-type:text/html; Charset=utf-8 ');    Require "lib/imghelper.php";    $imgHelper = new Imghelper ("Dir1");    $imgHelper->setoutputdir ("Dir2");    The default output is 1024 768 inferior than scaling and needs to be customized when $imgHelper->setoutputsize (1440,900);    $imgHelper->execution ();

LIB library code.
 "1024x768", "maxheight" = "768");        function __construct ($dir = ", $option = Array ()) {if (! $dir) return;        $this->srcdirs = $dir;        $this->srcfiles = $this->traversal ($dir);    $this->setoptions ($option); }/** * Set output directory * @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 is easy to handle.           $maxWidth = $this->_option["MaxWidth"];           $maxHeight = $this->_option["MaxHeight"];       $this->resize ($SRCIMG, $toFile, $maxWidth, $maxHeight);    Endforeach;    }//Zoom picture.       Private Function Resize ($srcImage, $toFile, $maxWidth =, $maxHeight = +, $imgQuality =100) {//Create directory directory!     $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); Case 2: $img = Imagecreatefromjpeg ($srcImage);                Break Case 3: $img = Imagecreatefrompng ($srcImage);            Break } $scale = min ($maxWidth/$width, $maxHeight/$height);                Find the bloom ratio 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; }/** * Sets the size of the output * @param string $width * @param string $height */Public function setoutputsize ($wi        DTH = "1024x768", $height = "768") {$_option = Array ("MaxWidth" + "$width", "maxheight" = "$height");    $this->setoptions ($_option);     }    /*** Set Optional Parameters * @param $option */Private Function setoptions ($option) {foreach ($option as $key =>$            val): if (Isset ($option [$key]) && $option [$key]) {$this->_option[$key] = $val;    } Endforeach;        }/** * Get all the files under the folder */Private Function Traversal ($path) {if (! $path) return array ();        $files = Array ();        if (!is_dir ($path)) return; foreach (Scandir ($path) as $file) {if ($file! = '. ' && $file! = ') {$path 2 = $path. '/' .                $file;                    if (Is_dir ($path 2)) {$temp = $this->traversal ($path 2);                $files = Array_merge ($files, $temp); } else {if ($this->isimg ($file)) {$files [] = $path. "/" .                    $file;    }}}} return $files; }/** * Determine if it is a picture * @param $filE * @return BOOL */Private Function isimg ($file) {$pInfo = PathInfo ($file);        $extention = $pInfo ["extension"]; Return Preg_match ("/(jpg) | (    PNG) |gif/i ", $extention);          }/** * Debug data */Public Function debug () {$this->pr ($this->srcfiles, "array of images to be processed.");          $this-&GT;PR ($this->srcdirs, "source directory");    $this-&GT;PR ($this->exportdir, "target directory"); The Private function PR ($array, $title = ' DEBUG ', $type = ' array ', $width = ') {/*** @ formatted output */$title. =        Date ("y-m-d h:i:s");        $WIDTHSTR = ""; if ($width) $widthStr = "width: $width".        "PX"; echo "
 
  
 
   $title";        echo ""; Print ("
   
");        if ($type = = ' json ') {  $array = Json_decode ($array);    }        Print_r ($array);        Print ("
"); echo ""; echo " "; }}



Reply to discussion (solution)

Just run a bit, found that there are too many pictures, running time is not enough, add a sentence ini_set (' max_execute_time ', 3600); To

Dizzy one of the above is wrong, corrected to Max_execution_time

The code is confiscated ~ ~ Very good.

Reply more than 30 floor, send today candid photo of beautiful woman!

... ...
Is it a bit? A little bit? A little bit?!
Reply more than 30 floor, send today candid photo of beautiful woman!

Haha, class closed, ....

$maxWidth = $this->_option["MaxWidth"];
$maxHeight = $this->_option["MaxHeight"];
Isn't it better to put it outside the loop?

The resize method looks bloated.

Come and see.

This is good, a collection, to use


Recently taken more than 3k pictures about 20G pictures, this thought the program was written well, happy in the operation of the conversion, who knows, when I slept not long, the computer encounter mother hand, direct power off type shutdown. Open a look, only to turn 400, run again, these 400 pictures will repeat the operation, so toss a bit of code, will be repeated removed, and additional logging function.

Within the class Imghelper.     Add the following code.   private $copyOverWrite = true;    Private $isLog = true;    /**     * Set whether logging     * @param $bool *    /Public Function Setislog ($bool)    {            $this->islog = $bool; c9/>}    /**     * Sets whether to overwrite     * @param $bool *     /public    function Setcopyoverwrite ($bool) {        $this- >copyoverwrite = $bool;    }    Logs are logged.    Private Function log ($str, $title = ' picture Assistant log ')    {        $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);    }


The function resize () is modified//appended to the first line. if (! $this->copyoverwrite && is_file ($toFile))//When set to not overwrite and the file already exists, skip {$this->log                  ("$toFile already exists, and the system is set to not overwrite, will do skip processing", "Operation Tip");            return; } $this->log ("Trying to generate $toFile");//modified Private Function Resize ($srcImage, $toFile, $maxWidth =, $maxHeig            HT = +, $imgQuality =100) {if (! $this->copyoverwrite && is_file ($toFile))//When set to not overwrite, and if the file already exists, skip                  {$this->log ("$toFile already exists, and the system is set to not overwrite, will do skip processing", "action tip");            return;            } $this->log ("Trying to build $toFile");            Create directory directory!            $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); Find out the proportion of bloom//...

Good advice, written too handy, has been modified!
$maxWidth = $this->_option["MaxWidth"];
$maxHeight = $this->_option["MaxHeight"];
Isn't it better to put it outside the loop?

The resize method looks bloated.

    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 is easy to handle.           $this->resize ($SRCIMG, $toFile, $maxWidth, $maxHeight);       Endforeach;    }

Very good ~mark study a bit ~

Technology flow changes life .... Wait for the landlord to put beautiful pictures

Code collection, the original landlord is working in Shenzhen

Come to Shenzhen for two years, have time to come out together, chat blowing water.
Code collection, the original landlord is working in Shenzhen

1. Look at your echo HTML tag, this is the first question, this program should be suitable for the command line execution, not Web mode

2. if ($width < $maxWidth | | $height < $maxHeight) return; I think there is a logic error, what is your plan?

3. Recursive directory with Recursivedirectoryiterator will be much more cool, manual (user discussion version) above there are many routines, so that you can write this kind of ability, to see if the routines are not difficult to master

4.resize algorithm can be more simple, think about it

5. Many pictures suggest using ImageMagick instead of GD, more efficient

6. "\ n" "/" Change to Php_eol and Directory_separator constants, compatible with win


Finally, a lot of pictures or tools to zoom it, professional software efficient and can control the output of the image quality
But you can use this kind of modification after processing the upload image, or the use of a small

Resize this method, directly from the Internet, I did not pay attention to the wording inside, here is not willing to go seriously, more is the rapid integration and implementation!
1. Look at your echo HTML tag, this is the first question, this program should be suitable for the command line execution, not Web mode

2. if ($width < $maxWidth | | $height < $maxHeight) return; I think there is a logic error, what is your plan?

3. Recursive directory with Recursivedirectoryiterator will be much more cool, manual (user discussion version) above there are many routines, so you can write this class ...

Do not struggle with efficiency what, the premise is the convenience of life

Imagick core three lines of code to complete the thumbnail, the problem is that you may not be imagick environment, or install a version mismatch, this toss, I'm almost finished.
$image = new Imagick ("Mypicture.png");
$image->thumbnailimage (Max, Max, true);
$image->writeimage ("Thumb.png");

The front is the word, can be completely ignored

My main meaning is, LZ, can you release the diagram first?

Use it more quickly, the code is beautiful instead of the secondary

Do not struggle on the #30 ah, it seems I should put 6 points apart 6 floors.

Oh, we look forward to the photos.

I came to see the beauty.

Landlord Quick Explosion photo

Come and join in the next ~

F5 is broken.

There's no one to pick up the scattered? Come on, cover to the 30 floor.

Fast speed

Plus look at the beautiful photos of the brothers up AH on the two floor

The brothers downstairs finally wait for you ....

Photo Nirvana

Code really good, the most important thing is to serve the life of the idea, too cool!
Looks like I'm on the 30 floor!!
The Jackpot!

Sorry, pictures in the home of the machine, home immediately fill up ~

Not a beautiful woman beating a meal.

I'm only interested in photos.

Personality guarantee, pictures from candid ~




Excuse me, is this the girl in the middle or the bottom?

echo    ' Do not hurry, tiger brother, you want to know the beauty of this kind of things, like flowers, need to have green leaves to foil will show her charming, you look at it again ';

Beautiful look, the code has been accepted!! Ha ha

Really is beautiful, but beautiful is not wearing a cottage clothes ah. "Never Cry" a little "y"?

Go out for a walk and relax. The programmers are going to take pictures on weekends.

Good things, collection, thank you!

Mark, we'll talk later.

Really is beautiful, but beautiful is not wearing a cottage clothes ah. "Never Cry" a little "y"?

Haha this can have

46 Floor Truth

F5 has broken oh, laughing at me ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.