I have written this method in my Image class that works like a charm.
IMPORTANT: Please note that this will output the image to the screen so you need to call this function inside a file like this:
Let's say you create thumb.php and put that function in there and than you have image.php where you have this:
Also note that this works for most image file types and will also preserve transparency for png and gif images. Not sure if you need that, but you can remove it from the end there if you don't..
Also note that this will scale the image to a width of your own choice, which I called it $scaled_size_in_pixels here.
Code: Select all
require_once("thumb.php");
echo thumb("/path/to/your/image.jpeg", $the_scaled_size_in_pixels);
And then in your html template file you go like:
Of course you could send the path via $_GET like this
Code: Select all
<img src="image.php?image_file=/path/to/image/file" />
I'm sure you get the drill.
Here's the function
Code: Select all
function thumb($image_file , $sz ="-1", $quality = "75"){
$this->image_file = $image_file;
$this->sz = $sz;
$this->quality = $quality;
$imgDat = @getimagesize($this->image_file);
$mime = $imgDat['mime'];
if ($imgDat[0] > $imgDat[1]+20) {
$tw = $this->sz;
$th = $imgDat[1]/($imgDat[0]/$tw);
} else {
$th = $this->sz;
$tw = $imgDat[0]/($imgDat[1]/$th);
}
if ($this->sz == "-1") {
$imNew = ImageCreateTrueColor($imgDat[0], $imgDat[1]);
}else{
$imNew = ImageCreateTrueColor($tw, $th);
}
if ($mime == 'image/gif') {
$imFile= ImageCreateFromGIF($this->image_file);
} else if ($mime == 'image/png') {
$imFile= ImageCreateFromPNG($this->image_file);
} else if ($mime == 'image/jpeg') {
$imFile= ImageCreateFromJpeg($this->image_file);
}
if ($this->sz == "-1") {
$res = imagecopyresampled ($imNew, $imFile, 0, 0, 0, 0, $imgDat[0], $imgDat[1], $imgDat[0], $imgDat[1]);
} else {
$res = imagecopyresampled ($imNew, $imFile, 0, 0, 0, 0, $tw, $th, $imgDat[0], $imgDat[1]);
}
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Content-Type: ".$mime);
header('Content-Disposition: inline; filename=test');
if ($mime == 'image/gif') {
imagealphablending($imNew, false);
imagesavealpha($imNew,true);
$transparent = imagecolorallocate($imNew, 0, 0, 0);
imagecolortransparent($imNew, $transparent);
$imFile= ImageCreateFromGIF($this->image_file);
imagegif($imNew);
} else if ($mime == 'image/png') {
imagealphablending($imNew, false);
imagesavealpha($imNew,true);
$transparent = imagecolorallocate($imNew, 0, 0, 0);
imagecolortransparent($imNew, $transparent);
$imFile= ImageCreateFromPNG($this->image_file);
imagepng($imNew);
} else if ($mime == 'image/jpeg') {
$imFile= ImageCreateFromJpeg($this->image_file);
imagejpeg($imNew);
}
imagedestroy($imNew);
}