php GD makeing thumbnails to a certain size

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jungabunga
    New Member
    • Mar 2007
    • 15

    php GD makeing thumbnails to a certain size

    heya guys, im trying to take a variable input file and make a thumbnail so my gallery pageloads are lower. i want all the thumbnails to end up around 15ish kb, i know my current settings dont display that - im still testing.
    it works on smaller files 250k, resizes to about 20ish k and 170k to about 3k, but i cant get it to resize bigger images and the while loop wont stop when the image reaches a certain size, i dont know where to go... pls help me debug this bugger ;)

    Code:
    $target_size=90000; // 7.5KB
    $initial_size=$target_path.$newfile;
    $filesize=filesize($initial_size);
    $file=$target_path.$newfile;
    $x=0;
    $reduction=($filesize*5)/100;
    $size = 0.9;
    while($filesize>$target_size){
    	$x++;
    	$save = $target_path."thumb_".$newname.".jpg";
    	$file = $file;
    	header('Content-type: image/jpeg') ; 
    	list($width, $height) = getimagesize($file) ; 
    	$modwidth = $width * $size; 
    	$modheight = $height * $size; 
    	$tn = imagecreatetruecolor($modwidth, $modheight) ; 
    	$image = imagecreatefromjpeg($file) ; 
    	imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; 
    	imagejpeg($tn, $save, 90) ;
    	$file = $target_path."thumb_".$newname.".jpg"; 
    	$filesize=$filesize-$reduction;
    	$size=$size-0.05;
    	}
    echo "resized $x times.";
  • pbmods
    Recognized Expert Expert
    • Apr 2007
    • 5821

    #2
    In a situation like this, I like to write all my variables to a file so I can keep track of what's going on.

    Basically, you want to take advantage of the fwrite function. fwrite will write to the file directly and immediately so you don't have to worry about whether you will see output if you stop the browser from trying to load the page.

    Naturally, you'll probably want to eventually write your own Debugger object, but for now, try something like this:

    [php]
    $reduction=($fi lesize*5)/100;
    $size = 0.9;

    // [DBuG]
    $debugFile = fopen('/path/to/debug/file.txt');

    while($filesize >$target_size ){
    $x++;
    .
    .
    .

    // // [DBuG]
    fwrite($debugFi le, <<<EOF
    AFTER RUN #$x:
    \$filesize = $filesize
    (etc.)


    EOF;

    $size=$size-0.05;
    }
    echo "resized $x times.";


    // [DBuG]
    fclose($debugFi le);
    [/php]

    After you're pretty sure your loop is definitely infinite, stop your browser (and kill the php process), then open up your debug file and take a look at what wasn't changing.

    Of course, this won't fix your problem, but it should help give you a better idea of exactly what is going on.

    Comment

    Working...