Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
Showing 21-21 of 21 total

Image resize

Resize an image, keeping proportions to a new width or a new height. oh, and it caches.
You'll need to setup a writable directory $_SERVER[ 'DOCUMENT_ROOT' ].'/images/cache/ to use it.
<?php

if (isset($_GET[ 'image' ]))
{
    $image = realpath($_SERVER[ 'DOCUMENT_ROOT' ].urldecode($_GET[ 'image' ]));
    
    if (!file_exists($image))
    {
        die ( 'no such image!' );
    }
} else {
    die ( 'Missing argument!' );
}

function between($x, $y, $z)
{
    return $x >= $y && $x <= $z;
}

function cachefilename( $o, $w, $h)
{
    return $_SERVER[ 'DOCUMENT_ROOT' ].'/images/cache/'.base64_encode( $o.$w.$h ).'jpeg';
}

$imageinfo = getimagesize($image);
$w = $imageinfo[0];
$h = $imageinfo[1];
// the 64 and 1024 are minimum and maximum, change to please
if (isset ($_GET[ 'width' ]) && between($_GET[ 'width' ], 64, 128))
{
    $resizedwidth = $_GET[ 'width' ];
    $wf = $w / $resizedwidth;
    $resizedheight = $h / $wf;

} else {
    // same here
    if (isset ($_GET[ 'height' ]) && between($_GET[ 'height' ], 64, 1024))
    {
        $resizedheight = $_GET[ 'height' ];
        $hf = $h / $resizedheight;
        $resizedwidth = $w / $hf;

    } else {
        $resizedwidth = 600;
        $wf = $w / $resizedwidth;
        $resizedheight = $h / $wf;
    }
}

if (file_exists( cachefilename($image, $resizedwidth, $resizedheight) ))
{
    header ("Content-type: image/jpeg");
    readfile(cachefilename($image, $resizedwidth, $resizedheight) );
} else {
    $img = imagecreatefromstring(file_get_contents( $image ));
    $thumb = imagecreatetruecolor($resizedwidth, $resizedheight);
    imagecopyresampled($thumb, $img, 0, 0, 0, 0, $resizedwidth, $resizedheight, $w, $h);
    header ("Content-type: image/jpeg");
    imagejpeg($thumb, cachefilename($image, $resizedwidth, $resizedheight), 70);
    readfile(cachefilename($image, $resizedwidth, $resizedheight) );
    imagedestroy($img);
    imagedestroy($thumb);
}

?>
« Newer Snippets
Older Snippets »
Showing 21-21 of 21 total