Jump to content

Image resize function


craygo

Recommended Posts

I put together this function to resize images. I wanted to post it so others can use it. If this is in the wrong place please feel free to move it or make a sticky somewhere.

 

you can call this file anything you like, I called it:

imageresize.php

<?php
header('Content-type: image/jpeg');
function resampimagejpg($maxwidth, $maxheight, $sourcefile, $imgcomp=0)
   {
   $g_imgcomp=100-$imgcomp;
   if(file_exists($sourcefile))
       {
       $g_is=getimagesize($sourcefile);
       $w_adjust = ($maxwidth / $g_is[0]);
       $h_adjust = ($maxheight / $g_is[1]);
       if($w_adjust <= $h_adjust)
           {
           $new_width=($g_is[0]*$w_adjust);
           $new_height=($g_is[1]*$w_adjust);
           }
           else
           {
           $new_width=($g_is[0]*$h_adjust);
           $new_height=($g_is[1]*$h_adjust);
           }
       	//SEARCHES IMAGE NAME STRING TO SELECT EXTENSION (EVERYTHING AFTER . )
    $image_type = strrchr($sourcefile, ".");

    //SWITCHES THE IMAGE CREATE FUNCTION BASED ON FILE EXTENSION
	switch($image_type) {
		case '.jpg':
			$img_src = imagecreatefromjpeg($sourcefile);
			break;
		case '.png':
			$img_src = imagecreatefrompng($sourcefile);
			break;
		case '.gif':
			$img_src = imagecreatefromgif($sourcefile);
			break;
		default:
			echo("Error Invalid Image Type");
			die;
			break;
		}
       $img_dst=imagecreatetruecolor($new_width,$new_height);
       imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $new_width, $new_height, $g_is[0], $g_is[1]);
       imagejpeg($img_dst);
       imagedestroy($img_dst);
       imagedestroy($img_src);
       return true;
       }
       else
       return false;
   }
resampimagejpg($_GET['width'], $_GET['height'], $_GET['source']);
?>

 

Now you can either just call the resize from a link like so

<img src="imageresize.php?width=200&height=200&source=images/myimage.jpg">

 

or if you have an images folder that you would like to loop through and show thumbnails

<?php
$dir = "images/";
if ($handle = opendir($dir)) {
   while (false !== ($file = readdir($handle))) {
     if(substr($file, 0, 1) != "."){  // this will remove the "." and ".."
            print '<a href="'.$dir.$file.'"><img src="imageresize.php?width=200&height=200&source=images/'.$file.'" border=0><a><br />';
     }
   }
   closedir($handle);
}
?>

 

Hope this comes in handy

 

Ray

Link to comment
https://forums.phpfreaks.com/topic/39480-image-resize-function/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.