开发者

PHP: If image too wide or tall downsize and constrain proportions.

I am guessing probably need to use GD image library for this but I need some help being pointed in the right direction.

I display an image on a page and if it is over 800px wide I want to downscale it to 800 px wide but sc开发者_如何学Cale the height proportionally and if its over 600px tall I want to do the same.

What's the best way of achieving this?


you can use this class for resizing


You can start by looking at exec("/usr/bin/convert {$current_image} -resize {$width}x{$height}\> -quality 100 $dest_image", $ret_val);
this will scale but keep aspect. full doc of imageMagick command line tool convert here: http://www.imagemagick.org/script/convert.php


I u have a $fileName (original image filename), the requiered $width and $height max values, call the resizeImage function. Then this function create a new file called $finalFileName.

resizeImage( imageCreateFrom( $fileName ),
             $finalFileName,
             $width,
             $height,
             false );

function resizeImage( $resSrc, $fileNameDst, $nwX, $nwY, $forceResize = true ) {
    $resSrcX = imagesx( $resSrc );
    $resSrcY = imagesy( $resSrc );
    if ( !$forceResize ) {
        if ( $resSrcX < $nwX ) {
            $nwX = $resSrcX;
        }
        if ( $resSrcY < $nwY ) {
            $nwY = $resSrcY;
        }
    }
    if ( $resSrcY / $resSrcX > $nwY / $nwX ) {
        $thumbY = $nwY;
        $thumbX = intval( $nwY * $resSrcX / $resSrcY );
    } else {
        $thumbX = $nwX;
        $thumbY = intval( $nwX * $resSrcY / $resSrcX );
    }
    $copyResource = imagecreatetruecolor( $thumbX, $thumbY );
    imagecopyresampled( $copyResource, $resSrc, 0, 0, 0, 0,
                        $thumbX, $thumbY,
                        $resSrcX, $resSrcY );
    preg_match( '#\.([^\.]*)$#', $fileNameDst, $match );
    $extension = $match[1];
    switch ( $extension ) {
        case 'gif':
            setTransparency( $copyResource, $resSrc );
            imagegif( $copyResource, $fileNameDst );
            break;
        case 'jpeg':
        case 'jpe':
        case 'jpg':
            imagejpeg( $copyResource, $fileNameDst );
            break;
        case 'png':
            setTransparency( $copyResource, $resSrc );
            imagepng( $copyResource, $fileNameDst );
            break;
    }
    imagedestroy( $copyResource );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜