Pages

Monday, October 17, 2011

Resizing images in a folder and putting into another folder

I visited Cox's Bazar on 30-07 to 02-08, 2011 with my colleagues. They snapped our happy memory in more than 500 pics of digital/mobile camera.

I found the sizes are quit large around 2M, more or less. So I decided to write some code to reduces the size and quality so the file size got reduced.


With the combination of 2 type of code, I wrote the code:
1. Directory content reading. and
2. Image resizing and saving.

Configurations:
set_time_limit: The function parameter - larger need to be the value if more pics are there.
source directory: the $dir variable
destination directory:  the $dest dir inside the `imageresize` function

Preparation:
A destination folder is to be created before, I do not write code to create destination directory.

Condition:
* I wrote the code only to resize JPEG type of image.
* I tested it on a Windows 7 box and in Wamp.

The code:


<?php

set_time_limit(300);

function imageresize($v, $i, $dir ) {

    $dest='D:/Cox\'s Bazzar/100SSCAM-small/';

    if( stripos( $v, '.jpg') ) {

        $filename = $dir.$v;

        $percent = 0.5;




        // Content type

        header('Content-Type: image/jpeg');




        // Get new sizes

        list($width, $height) = getimagesize($filename);

        $newwidth = $width * $percent;

        $newheight = $height * $percent;




        // Load

        $thumb = imagecreatetruecolor($newwidth, $newheight);

        $source = imagecreatefromjpeg($filename);




        // Resize

        imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);




        // Output

        imagejpeg($thumb, $dest.$v, 40);

        

    } //else echo $v, '=>',$i;

}//end function imageresize




$dir    = "D:/Cox's Bazzar/100SSCAM/";

$files1 = scandir($dir);

//$files2 = scandir($dir, 1);




array_walk($files1, 'imageresize' , $dir);

//print_r($files1);

//print_r($files2);

?>

No comments :

Post a Comment