Wednesday, December 20, 2017

php - imagemagick for thumbnail gallery making

Just here for reference is a script I used to make a simplistic thumbnail gallery with links to fullsize, full of copy and paste bits from a few sources. You need a folder named thumb/ where it will dump the smaller versions. It uses Imagemagick thumbnailImage to set a maximum size of 300x300 but preserve the aspect ration and then dumps HTML I copy and paste into the index. This is for a gallery archive for my real-world Wall o' Peeps




<?
$skips = "";
$files = array_diff(scandir("."), array('..', '.'));
foreach($files as $i => $justname){

    $UPPERCASE = strtoupper($justname);

    $UPPERCASE = strtoupper($justname);
    if(endsWith($UPPERCASE,".JPG") || endsWith($UPPERCASE,".JPEG") ){

        $filename = $justname;
        $image = new Imagick($filename); 
        autorotate($image);
        $d = $image->getImageGeometry(); 
        $w = $d['width']; 

    
            $image->thumbnailImage(300,300,true);

            $image->writeImage("thumb/".$filename);
            $d2 = $image->getImageGeometry(); 
            $w2 = $d2['width']; 
            $h2 = $d2['height'];
            print htmlspecialchars("<a href=\"$justname\"><img width=\"$w2\" height=\"$h2\" src=\"thumb/".$justname."\"></a>\n\n");
            print "<br><br>\n";
       

    } else {
    $skips = $skips . "  skip $justname<br><br>";
    }
}
print "<br><br>$skips";

function autorotate(Imagick $image)
{
    switch ($image->getImageOrientation()) {
    case Imagick::ORIENTATION_TOPLEFT:
        break;
    case Imagick::ORIENTATION_TOPRIGHT:
        $image->flopImage();
        break;
    case Imagick::ORIENTATION_BOTTOMRIGHT:
        $image->rotateImage("#000", 180);
        break;
    case Imagick::ORIENTATION_BOTTOMLEFT:
        $image->flopImage();
        $image->rotateImage("#000", 180);
        break;
    case Imagick::ORIENTATION_LEFTTOP:
        $image->flopImage();
        $image->rotateImage("#000", -90);
        break;
    case Imagick::ORIENTATION_RIGHTTOP:
        $image->rotateImage("#000", 90);
        break;
    case Imagick::ORIENTATION_RIGHTBOTTOM:
        $image->flopImage();
        $image->rotateImage("#000", 90);
        break;
    case Imagick::ORIENTATION_LEFTBOTTOM:
        $image->rotateImage("#000", -90);
        break;
    default: // Invalid orientation
        break;
    }
    $image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
    return $image;
}


function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

function endsWith($haystack, $needle)
{
    $length = strlen($needle);

    return $length === 0 || 
    (substr($haystack, -$length) === $needle);
}

?>

No comments:

Post a Comment