Nov
11 d.
2007

Generating JPG thumbnail with PHP

In case you need to generate image thumbnail, you can use this simple PHP function. It takes 4 parameters: source filename, thumbnail filename, thumbnail width and height. Before resizing the image, this function crops it proportionaly, this way ensuring that thumbnail image is not streched.

Sample usage:

    try {
        makeJpgThumbnail('image.jpg', 'thumb.jpg', 80, 100);
    } catch (Exception $e) {
        echo $e->getMessage();
    }

And finaly the function itself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    /**
     * Creates and saves JPEG image thumbnail.
     *
     * @author    Tomas Liubinas
     * @copyright None. You can use and modify this method as you want.
     *            Just leave the comment if you like it.
     *
     * @param string $sOriginalPath Original JPEG image file name (including path)
     * @param string $sThumbPath    Target Thumbnail file name
     * @param int    $iThumbWidth   Thumbnail width
     * @param int    $iThumbHeight  Thumbnail height
     *
     * @throws Exception
     *
     */
    function makeJpgThumbnail($sOriginalPath, $sThumbPath, $iThumbWidth, $iThumbHeight)
    {
        //get original size
        $aSize = @getimagesize($sOriginalPath);
 
        if ($aSize === false || $aSize[2] != 2)
            throw new Exception('JPEG image error');
 
        $iImageWidth = $aSize[0];
        $iImageHeight = $aSize[1];
        $iImageType = $aSize[2];
 
        //get cropp size and offset
        $fImageRatio = $iThumbHeight/$iThumbWidth;
        if ($iImageHeight > $iImageWidth * $fImageRatio) {
            //crop bottom
            $iCropWidth = $iImageWidth;
            $iCropHeight =  (int) ($iImageWidth * $fImageRatio);
            $iOffsetX = 0;
            //try to take UPPER part of source image by cutting the bottom off
            $iOffsetY = 0;
            //uncomment this in order to take MIDDLE part of source image
            //$iOffsetY = (int) (($iImageHeight - $iCropHeight) / 2);
        } else {
            //crop sides
            $iCropWidth = (int) ($iImageHeight / $fImageRatio);
            $iCropHeight = $iImageHeight;
            $iOffsetX = (int) (($iImageWidth - $iCropWidth) / 2);
            $iOffsetY = 0;
        }
 
        //create thumbnail
        $rSource = imagecreatefromjpeg($sOriginalPath);
        $rImage = imagecreatetruecolor($iThumbWidth, $iThumbHeight);
        imagecopyresampled($rImage, $rSource, 0, 0, $iOffsetX, $iOffsetY,
                           $iThumbWidth, $iThumbHeight, $iCropWidth, $iCropHeight);
        imagejpeg($rImage, $sThumbPath, 95);
    }

Leave a Reply