61924

Cropped thumbnail function

— Frank — ? Comments

Just a simple function that I would like to add to ImgBrowz0r. I'm not sure when, but it's going to be added. It's not really advanced. Just something simple. :)

It grabs a random part (with the size of the thumbnail) of the original image and saves that as a thumbnail. Transparent GIF and PNG images are supported.

function make_random_cropped_thumbnail($filepath, $t_width, $t_height)
{
    $thumbnail_path = dirname($filepath).'/t_'.basename($filepath);
    list($image_width, $image_height, $image_type) = getimagesize($filepath);

    // Open the image so we can make a thumbnail
    if ($image_type === 3)
        $image = imagecreatefrompng($filepath);
    else if ($image_type === 2)
        $image = imagecreatefromjpeg($filepath);
    else if ($image_type === 1)
        $image = imagecreatefromgif($filepath);
    else
        return false;

    // Create an image for the thumbnail
    $thumbnail = imagecreatetruecolor($t_width, $t_height);

    // Preserve transparency in PNG
    if ($image_type === 3)
    {
        $alpha_color = imagecolorallocatealpha($thumbnail, 0, 0, 0, 127);
        imagefill($thumbnail, 0, 0, $alpha_color);
        imagesavealpha($thumbnail, true);
    }

    // Preserve transparency in GIF images
    else if ($image_type === 1 && ($transparent_index = imagecolortransparent($image)) >= 0)
    {
        $transparent_color = imagecolorsforindex($image, $transparent_index);
        $transparent_index = imagecolorallocate($thumbnail, $transparent_color['red'],
                                                $transparent_color['green'], $transparent_color['blue']);
        imagefill($thumbnail, 0, 0, $transparent_index);
        imagecolortransparent($thumbnail, $transparent_index);
    }

    // Generate coordinates
    $src_x = mt_rand(0, $image_width-$t_width);
    $src_y = mt_rand(0, $image_height-$t_height);

    // Copy and crop image
    imagecopyresampled($thumbnail, $image, 0, 0, $src_x, $src_y, $image_width, $image_height, $image_width, $image_height);

    // Save the thumbnail, but first check what kind of file it is
    if ($image_type === 3)
        imagepng($thumbnail, $thumbnail_path);
    else if ($image_type === 2)
        imagejpeg($thumbnail, $thumbnail_path, 85);
    else if ($image_type === 1)
    {
        imagetruecolortopalette($thumbnail, true, 256);
        imagegif($thumbnail, $thumbnail_path);
    }

    // Destroy image resources
    imagedestroy($image);
    imagedestroy($thumbnail);

    // Return the path to the thumbnail
    return $thumbnail_path;
}

Usage:

make_random_cropped_thumbnail('image.jpg', 300, 300);

Share

Comments