[英]PHP Crop an image found in a subfolder to display as thumb
我確實在某個地方找到了此腳本,並且似乎可以正常工作。 唯一的問題是,即使應該將其裁剪為正方形,它也會輸出與原始拇指完全相同的大小比例。
$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>';
?>
有什么錯誤的主意嗎?
謝謝!
您絕對沒有錯誤處理,只是假設沒有錯誤,因此這兩行:
$dir = "*/";
$image2 = imagecreatefromjpeg($dir."main.jpg");
將完全等同於
$image2 = imagecreatefromjpeg("*/main.jpg");
ICFJ() 不接受通配符,時間。
由於不檢查錯誤,因此您永遠不會看到icfj()返回的布爾值FALSE,表示失敗。
抱歉,您對情況的誤解...我忘了在IMG標簽中添加一些CSS樣式,以便圖像的位置對應於$ thumbPosition,並且對應於projects-img-container div的寬度和高度為200像素。
現在一切都按預期進行!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.