Create thumbnail images with PHP

I developed a function which creates a thumbnail for a given image in a predefined size. Please note that this function was created to be used within a WordPress plugin so it uses paths related to WordPress but these paths can be easily adapted to be used without WordPress.

Preamble
PHP file:
/var/www/wordpress/wp-content/plugins/thumbnail_generator/thumbnail_generator.php
Sample image:
/var/www/wordpress/wp-content/plugins/thumbnail_generator/pictures/album1/picture1.jpeg
Sample image size:
1600×1066 pixels

My function will create a thumbnail called picture1.jpeg.png with a width of 100px and an appropriate height in a directory called:
/var/www/wordpress/wp-content/plugins/thumbnail_generator/thumbnails/pictures/album1/.

thumbnail_generator.php

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
createThumbnail('pictures/album1/picture1.jpeg', 100);
 
function createThumbnail($relativePath, $resizedWidth)
{
  $thumbnailDirectory = plugin_dir_path(__FILE__) . 'thumbnails/';
  $imageFile = plugin_dir_path(__FILE__) . $relativePath;
  // Determine image type
  if (preg_match('/[.](jpe?g?|jfif|tiff)$/', $imageFile))
    $image = imagecreatefromjpeg($imageFile);
  else if (preg_match('/[.](gif)$/', $imageFile))
    $image = imagecreatefromgif($imageFile);
  else if (preg_match('/[.](png)$/', $imageFile))
    $image = imagecreatefrompng($imageFile);
  // Calculate the thumbnail size (depending on the image aspect ratio)
  if (isset($image))
  {
    $width = imagesx($image);
    $height = imagesy($image);
    $resizedHeight = round(($height * ($resizedWidth / $width)), 0);
    $thumbnail = imagecreatetruecolor($resizedWidth, $resizedHeight);
    imagecopyresized($thumbnail, $image, 0, 0, 0, 0, $resizedWidth, $resizedHeight, $width, $height);
    // Save thumbnail to subdirectory
    $slashPosition = strrpos($relativePath, '/');
    $thumbnailName = substr($relativePath, $slashPosition);
    $thumbnailDirectory = $thumbnailDirectory . substr($relativePath, 0, $slashPosition);
    if (!file_exists($thumbnailDirectory))
      mkdir($thumbnailDirectory, 0755, true);
    imagepng($thumbnail, $thumbnailDirectory . $thumbnailName . '.png', 0);
  }
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.