Return to Snippet

Revision: 8906
at October 13, 2008 12:27 by Jenhale


Initial Code
<?php
function resampimagejpg( $forcedwidth, $forcedheight, $sourcefile, $destfile )
{
    $fw = $forcedwidth;
    $fh = $forcedheight;
    $is = getimagesize( $sourcefile );
    if( $is[0] >= $is[1] )
    {
        $orientation = 0;
    }
    else
    {
        $orientation = 1;
        $fw = $forcedheight;
        $fh = $forcedwidth;
    }
    if ( $is[0] > $fw || $is[1] > $fh )
    {
        if( ( $is[0] - $fw ) >= ( $is[1] - $fh ) )
        {
            $iw = $fw;
            $ih = ( $fw / $is[0] ) * $is[1];
        }
        else
        {
            $ih = $fh;
            $iw = ( $ih / $is[1] ) * $is[0];
        }
        $t = 1;
    }
    else
    {
        $iw = $is[0];
        $ih = $is[1];
        $t = 2;
    }
    if ( $t == 1 )
    {
        $img_src = imagecreatefromjpeg( $sourcefile );
        $img_dst = imagecreatetruecolor( $iw, $ih );
        imagecopyresampled( $img_dst, $img_src, 0, 0, 0, 0, $iw, $ih, $is[0], $is[1] );
        if( !imagejpeg( $img_dst, $destfile, 90 ) )
        {
            exit( );
        }
    }
    else if ( $t == 2 )
    {
        copy( $sourcefile, $destfile );
    }
}
?>

Initial URL
http://www.netlobo.com/php_image_resize_gd2.html#

Initial Description
To use the resize function you must pass in the forced width, forced height, source image, and destination image. The function then uses the GD2 library functions to read the source image's size. It will then calculate the new image's size based off of the forced width and height. This function will maintain the original image's aspect ratio so your image won't look distorted. It won't change the source image at all but when the function is done running you will end up with the destination image which is resized to the dimensions you passed into the function. As far as I know, this function requires the GD2 library although you might be able to get it to work with the GD1 library. The GD library extension must be enabled in PHP before you can use GD2 functions so keep that in mind as well. You can use the PHP function phpinfo() to see if GD2 is enabled or to see what version of the GD library your server is using.

Initial Title
Resizing an Image Using PHP

Initial Tags
php, resize, image

Initial Language
PHP