Jump to content

Create a thumbnail from an image in PHP


fer987

Recommended Posts

Hi! my code uploads an image and saves it to an upload folder, but I want to create a thumbnail of it.

 

For example, if I upload a 1400x1000 JPG, I would like to resize the image and it has to respect the proportion given a maximum size.

 

if I say the maximum width/height is 250px, the image should be thumbnailed according to the max height/width, and in proportion with the width/height

 

Thanks in advance

 

Fernando

Link to comment
https://forums.phpfreaks.com/topic/237832-create-a-thumbnail-from-an-image-in-php/
Share on other sites

There are plenty of such scripts freely available if you look. below is some code I have laying around which should work:

 

function createThumb($src_file, $dst_w, $dst_h)
{
    //Validate that valid sizes and readable image passed
    if ($dst_w<1 || $dst_h<1) { return false; }
    if (!list($src_w, $src_h, $src_type) = @getimagesize($src_file)) { return false; }

    //Supported image types & the functions to use
    $createFromSource = array(
        IMAGETYPE_JPEG => 'imagecreatefromjpeg',
        IMAGETYPE_GIF  => 'imagecreatefromgif',
        IMAGETYPE_PNG  => 'imagecreatefrompng',
        IMAGETYPE_WBMP => 'imagecreatefromwbmp',
        IMAGETYPE_XBM  => 'imagecreatefromwxbm',
    );

    //Validate that image type is supported
    if (!$createFromSource[$src_type]) { return false; }

    //Default values for thumb creation
    $dst_x=0; $dst_y=0; $src_x=0; $src_y=0;

    //Resize based upon source/destination ratios
    $ratio = min(($dst_w/$src_w), ($dst_h/$src_h));
    $dst_h  = $src_h * $ratio;
    $dst_w  = $src_w * $ratio;

    //Read the source image
    $src_image = $createFromSource[$src_type]($src_file);

    //Create the thumb
    $dst_image = imagecreatetruecolor($dst_w, $dst_h);
    imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
    return $dst_image;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.