I've seen a lot of "I can't get the script to work", and "But that doesn't actually resize the image!", and I got to thinking about what I've worked on recently using the GD libraries, and I found this very small random image rotation script that I wrote for my personal site. The code is listed below, and it allows for setting the width, height and quality of the image. I'm sure that you can easily modify it to show a specific image with little effort. ^ ^
PHP Code:
<?php
//rotate.php - Random Image Rotation Script -
$folder = './my_gallery';
$fileArray = glob("$folder/*.jpg");
$w = 150; // default width.
$quality = 80; // default quality.
$h = -1; // just sets the variable, in case the query string doesn't include it.
srand();
$idx = rand(0,count($fileArray) - 1);
$fileName = $fileArray[$idx];
$time = date ("l, F jS, Y g:i:s A");
foreach ($_GET as $key => $value) {
$$key = stripslashes($value);
}
list($srcWidth, $srcHeight) = getimagesize($fileName);
$srcImg = ImageCreateFromJPEG($fileName);
$aspectRatio = $srcWidth / $srcHeight;
$h = ($h != -1) ? $h : ($w / $aspectRatio); // Makes sure that the image is properly proportioned
$dstImg = imagecreatetruecolor($w, $h);
imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $w, $h, $srcWidth, $srcHeight); // I've noticed that on larger images, resampling is a bit slower than simple resizing, but this produces a MUCH better image.
header("Content-type: image/jpeg");
imagejpeg($dstImg,"",$quality);
imagedestroy($srcImg);
imagedestroy($dstImg);
?>
/*
The image is called with the following HTML tag:
<img src="rotate.php?w=100&q=80">
where w is the images width, and q is the images JPEG quality.
Note that I left off any width or height quantifiers in the HTML tag. While poor coding practice, it proves the resizing of the image indeed works.
*/
Below is the final product, in triplicate:
75 px width, 100% quality
100 px width, 67% quality
125 px width, 33% quality
Hope this helps. ^ ^
Bookmarks