PHP临时缩略图


PHP temporary thumbnail

我不是在保存图像,我只是想按百分比缩小图像,然后在网页上显示它

我知道我可以使用getimagesize来获得高度宽度,但如何正确缩放?

您可以使用这样的函数。

请参阅http://tutorialfeed.net/development/scale-an-image-using-php

 function create_thumb( $imgSrc, $thumbnail_width, $thumbnail_height, $dest_src, $ext )
    {
        //getting the image dimensions
        list( $width_orig, $height_orig ) = getimagesize( $imgSrc );  
        // Check if the images is a gif
        if( $ext == 'gif' )
        {
            $myImage = imagecreatefromgif($imgSrc);
        }
        // Check if the image is a png
        elseif( $ext == 'png' )
        {
            $myImage = imagecreatefrompng($imgSrc);
        }
        // Otherwise, file is jpeg
        else
        {
            $myImage = imagecreatefromjpeg($imgSrc);
        }
        // Find the original ratio
        $ratio_orig = $width_orig / $height_orig;
        // Check whether to scale initially by height or by width
        if( $thumbnail_width / $thumbnail_height > $ratio_orig )
        {
            $new_height = $thumbnail_width/$ratio_orig;
            $new_width  = $thumbnail_width;
        }
        else
        {
            $new_width      = $thumbnail_height*$ratio_orig;
            $new_height = $thumbnail_height;
        }
        $x_mid = $new_width / 2;  //horizontal middle
        $y_mid = $new_height / 2; //vertical middle
        $process = imagecreatetruecolor( round( $new_width ), round( $new_height ) ); 
        // Scale the image down and the reduce the other axis to create the thumbnail
        imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
        $thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
        imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)),   $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);
        // Depending on the file extension, save the file
        if( $ext == 'gif' )
        {
            imagegif( $thumb, $dest_src );
        }
        elseif( $ext == 'png' )
        {
            imagepng( $thumb, $dest_src );
        }
        else
        {
            imagejpeg( $thumb, $dest_src, 100 );
        }
        // Remove rubbish file data
        imagedestroy($process);
        imagedestroy($myImage);
        // Return thumb ( success / fail )
        return $thumb;
    }

您可以使用ImageWorkshop的resizeInPorcent()方法(使用GD库的库):http://phpimageworkshop.com/doc/17/resizing.html

例如:

<?php
$myImage->resizeInPourcent(50, 50); // Resize to get 50% width and height