繁体   English   中英

PHP裁剪在子文件夹中找到的图像以显示为拇指

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM