Create a thumbnail in PHP with imagemagick and rename accordingly

Written by - 0 comments

Published on March 7th 2019 - last updated on March 13th 2019 - Listed in PHP


As I'm programming my new blog, I am also renewing the admin section. When I created the first version with the "article" system, I always had to create an article first and then later upload pictures to the article.

In the new version this can be done while I write the initial article. I've been using Xinha as editor since 2011 and was always happy with it. I was ready to ditch Xinha for another editor (e.g. tinymce) because what was really missing was a direct file uploader. Looks like Xinha got this now with the plugin MootoolsFileManager.

Xinha MootoolsFileManager

Once I got the plugin to work, I had yet to figure out a way how thumbnails would be created and would be saved besides the original name with a "_tn", right before the file suffix.

In the MootoolsFileManager plugin folder, there is a file "mootools-filemanager/Assets/Connector/FileManager.php". This particular file is in charge for the image uploads and resizing. Although there is resizing involved, it basically only resizes the uploaded picture if it's larger than a defined height and width. This is handled by the following part of the PHP script:

if (FileManagerUtility::startsWith($mime, 'image/'))
{
  if (!empty($resize_imgs))
  {
    $img = new Image($file);
    $size = $img->getSize();
    // Image::resize() takes care to maintain the proper aspect ratio, so this is easy
    // (default quality is 100% for JPEG so we get the cleanest resized images here)
    $img->resize($this->options['maxImageDimension']['width'], $this->options['maxImageDimension']['height'])->save();
    unset($img);

    // source image has changed: nuke the cached metadata and then refetch the metadata = forced refetch
    $meta = $this->getFileInfo($file, $legal_url, true);
  }
}

To create the thumbnail, I decided to use the PHP extension "Imagemagick" and use the $file value. To create a thumbnail, there is a dedicated function available: thumbnailImage. However I read the comment from user "Jarrod" and decided to use his code for the resizing and compression.

First define the size of the thumbnail, followed by creating a new Imagick object. This uses the already defined $file value.After this the resizing and compression happens:

$tnsize1=500;
$image = new Imagick($file);
if($image->getImageHeight() <= $image->getImageWidth()) {
  // Resize image using the lanczos resampling algorithm based on width
  $image->resizeImage($tnsize1,0,Imagick::FILTER_LANCZOS,1);
} else {
  // Resize image using the lanczos resampling algorithm based on height
  $image->resizeImage(0,$tnsize1,Imagick::FILTER_LANCZOS,1);
}
// Set to use jpeg compression
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
// Set compression level (1 lowest quality, 100 highest quality)
$image->setImageCompressionQuality(75);
// Strip out unneeded meta data
$image->stripImage();

Now to the part where I struggled: I wanted to write the thumbnail to the same location as the original file just with a minor file name change:

$image->writeImage($_SERVER['DOCUMENT_ROOT']."/graph/news/thumbs/$file");

This created the following error message when I uploaded a new picture:

unable to open image `/path/to/website/graph/news/test//path/to/website/graph/news/5964444389069276856_1.jpg': No such file or directory @ error/blob.c/OpenBlob/2701

But $file obviously contains the whole path of the file, not just the filename. Now I needed to find a way to get the filename from $file.

To split the full path into different variables, the PHP function "pathinfo" can be used:

$imagefilename = pathinfo($image->getImageFilename());
echo "DEBUUUG Filename" . $imagefilename['filename'] ."
";
echo "DEBUUUG Basename " . $imagefilename['basename'] ."
";
echo "DEBUUUG Extension " . $imagefilename['extension'] ."
";

This gives the following output:

DEBUUUG Filename 3536899305055346748_account_id_1
DEBUUUG Basename 3536899305055346748_account_id_1.jpg
DEBUUUG Extension jpg

Using these values I can now rename and write the thumbnail into the same location as the original file:

$image->writeImage($_SERVER['DOCUMENT_ROOT']."/graph/news/thumbs/".$imagefilename['filename']."_tn.".$imagefilename['extension']);
$image->destroy();



Add a comment

Show form to leave a comment

Comments (newest first)

No comments yet.