Reputation: 73
I did found this script somewhere and it seems to be working. The only problem is that it outputs a thumb exactly the same size ratio than the original even though they are supposed to be cropped to a square...
$dir = "*/";
$images = glob($dir."main.jpg" );
echo '<div class="projects-container">';
foreach( $images as $image ) {
$dn = dirname($image);
$thumbsDir = $dn; // path to the thumbnails destination directory
$imageName = "main.jpg"; // returns "cheeta.jpg"
$thumbnail = $thumbsDir.$imageName; // thumbnail full path and name, i.e "./gallery/thumbs/cheeta.jpg"
// for each image, get width and height
$imageSize = getimagesize( $image ); // image size
$imageWidth = $imageSize[0]; // extract image width
$imageHeight = $imageSize[1]; // extract image height
// set the thumb size
if( $imageHeight > $imageWidth ){
// images is portrait so set thumbnail width to 100px and calculate height keeping aspect ratio
$thumbWidth = 200;
$thumbHeight = floor( $imageHeight * ( 200 / imageWidth ) );
$thumbPosition = "margin-top: -" . floor( ( $thumbHeight - 200 ) / 2 ) . "px; margin-left: 0";
} else {
// image is landscape so set thumbnail height to 100px and calculate width keeping aspect ratio
$thumbHeight = 200;
$thumbWidth = floor( $imageWidth * ( 200 / $imageHeight ) );
$thumbPosition = "margin-top: 0; margin-left: -" . floor( ( $thumbWidth - 200 ) / 2 ) . "px";
} // END else if
// verify if thumbnail exists, otherwise create it
if ( !file_exists( $thumbnail ) ){
$createFromjpeg = imagecreatefromjpeg( $image );
$thumb_temp = imagecreatetruecolor( $thumbWidth, $thumbHeight );
imagecopyresized( $thumb_temp, $createFromjpeg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imageWidth, $imageHeight );
imagejpeg( $thumb_temp, $thumbnail );
} // END if()
echo '<div class="projects">';
echo '<div class="projects-img-container">';
echo" <a href='".$dn."'><img class='img-projet' src='". '/projects/' . $thumbnail . "'/></a>";
echo '</div>';
echo '</div>';
}
echo '</div>';
?>
Any idea of what can be wrong?
Thank you!
Upvotes: 2
Views: 135
Reputation: 73
Sorry for the misunderstanding of the situation... I've forgot to add some CSS style in the IMG tag so that the position of the image corresponds to $thumbPosition and to the projects-img-container div to have a width and height of 200px.
Everything works as supposed now!
Upvotes: 1
Reputation: 360772
You have absolutely NO error handling and simply assuming nothing could ever go wrong, so these two lines:
$dir = "*/";
$image2 = imagecreatefromjpeg($dir."main.jpg");
will be exactly equivalent to
$image2 = imagecreatefromjpeg("*/main.jpg");
icfj() does NOT accept wildcards, period.
Since you don't check for errors, you never see the boolean FALSE that icfj() returned, signifying failure.
Upvotes: 3