Create image thumbnail with PHP

A guide on how to create an image thumbnail with PHP using the GD library. This PHP code helps resize an original image to a custom thumbnail size.

<?php
function createThumbnail($source_image_path, $thumbnail_path, $thumb_width) {
    // Get original image info
    list($width, $height, $image_type) = getimagesize($source_image_path);

    // Calculate thumbnail dimensions
    $thumb_height = intval($height * $thumb_width / $width);

    // Create a blank thumbnail
    $thumbnail = imagecreatetruecolor($thumb_width, $thumb_height);

    // Create image from source file
    switch ($image_type) {
        case IMAGETYPE_GIF:
            $source_image = imagecreatefromgif($source_image_path);
            break;
        case IMAGETYPE_JPEG:
            $source_image = imagecreatefromjpeg($source_image_path);
            break;
        case IMAGETYPE_PNG:
            $source_image = imagecreatefrompng($source_image_path);
            break;
        default:
            return false;
    }

    // Resize the source image into the thumbnail
    imagecopyresampled($thumbnail, $source_image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);

    // Save the thumbnail
    switch ($image_type) {
        case IMAGETYPE_GIF:
            imagegif($thumbnail, $thumbnail_path);
            break;
        case IMAGETYPE_JPEG:
            imagejpeg($thumbnail, $thumbnail_path, 90); // Quality 90%
            break;
        case IMAGETYPE_PNG:
            imagepng($thumbnail, $thumbnail_path);
            break;
    }

    // Free up memory
    imagedestroy($source_image);
    imagedestroy($thumbnail);

    return true;
}

// Use the function to create a thumbnail
$source_image = 'source_image.jpg';
$thumbnail_image = 'thumbnail_image.jpg';
$thumbnail_width = 150;

if (createThumbnail($source_image, $thumbnail_image, $thumbnail_width)) {
    echo "Thumbnail created successfully!";
} else {
    echo "Failed to create thumbnail.";
}
?>

Detailed explanation:

  1. Get original image info:

    • getimagesize($source_image_path): Retrieves the dimensions and type of the original image.
  2. Calculate thumbnail dimensions:

    • $thumb_height = intval($height * $thumb_width / $width): Calculates the height for the thumbnail, maintaining the aspect ratio of the original image.
  3. Create a blank thumbnail:

    • imagecreatetruecolor($thumb_width, $thumb_height): Creates a blank canvas for the thumbnail.
  4. Create image from source file:

    • Use imagecreatefromgif, imagecreatefromjpeg, and imagecreatefrompng to generate an image resource based on the image type (GIF, JPEG, PNG).
  5. Resize the source image into the thumbnail:

    • imagecopyresampled(): Resizes the source image into the thumbnail, preserving quality.
  6. Save the thumbnail:

    • Save the thumbnail in the same format as the original image using imagegif, imagejpeg, or imagepng.
  7. Free up memory:

    • imagedestroy(): Frees the memory associated with the image resources to avoid memory leaks.
  8. Use the function:

    • Executes the function to create the thumbnail from the original image and saves it as a new file.

PHP Version:

This code can run on PHP versions from 5.0 and above, requiring the GD extension for image processing.



Related

How to Automatically Generate a Table of Contents for Articles Using PHP

This article guides you on how to automatically create a table of contents for your articles using PHP, utilizing the `DOMDocument` class to parse HTML and build a structured table of contents with headers.
JSON Web Token (JWT) Authentication with PHP

A guide on using JSON Web Token (JWT) for authentication in PHP. Using JWT ensures secure transmission of information between client and server and is easy to implement in web applications.
Example of Strategy Pattern in PHP

A guide on the Strategy Pattern in PHP with a concrete example, explaining how to implement and use this design pattern in object-oriented programming.
How to check for a substring in a string in PHP

A guide on how to use the `strpos` function in PHP to check if a substring exists within a larger string. This is a simple and efficient way to handle string operations in PHP.
Creating a Simple Chat Application Using Socket.IO in PHP

A step-by-step guide to creating a simple chat application using Socket.IO in PHP, helping you understand how to utilize WebSocket for real-time communication.
Example of Factory Pattern in PHP

A guide on the Factory Pattern in PHP with a concrete example, explaining how to implement and use this design pattern in object-oriented programming.
Guide to reading Excel files in PHP

A comprehensive guide on how to read content from Excel files (.xlsx, .xls) using PHP, utilizing the PHPExcel library, including installation and implementation steps.
Convert accented Unicode characters to non-accented in PHP

A guide on how to convert accented Unicode characters in the Vietnamese alphabet to non-accented letters using PHP. This PHP code efficiently handles Vietnamese text processing.
How to extract numbers from a string in PHP

This article demonstrates how to extract numbers from a string in PHP using various methods such as regex (regular expressions), built-in functions like `preg_match_all`, `filter_var`, and manual approaches.
Prevent XSS (Cross-site Scripting) using PHP

A guide on how to prevent XSS (Cross-site Scripting) in PHP by filtering and escaping user input, ensuring website security against XSS vulnerabilities.

main.add_cart_success