phpjpegimagickfile-extensionfile-put-contents

PHP: When I save JPG image the file extension is always missing


I wrote a tiny script to create previews of all JPG images in a directory and save them into another directory. But the file extension .jpg is always missing. I really do not understand why.

foreach( glob(dirname(__FILE__)."/../../img/plakate/full/*.jpg") as $img ){

  // key
  $key = basename($img,'.jpg').PHP_EOL;

  // save preview
  $thumb = new Imagick($img);
  $thumb->setImageCompression(Imagick::COMPRESSION_JPEG);
  $thumb->setImageCompressionQuality(10);
  $thumb->resizeImage(50,0,Imagick::FILTER_LANCZOS,1);
  $thumb->writeImage("lib/img/plakate/preview/{$key}.jpg");
  $thumb->destroy();

}

I also tried this which results in the same:

foreach( glob(dirname(__FILE__)."/../../img/plakate/full/*.jpg") as $img ){

  // key
  $key = basename($img,'.jpg').PHP_EOL;

  // save preview
  $thumb = new Imagick($img);
  $thumb->setImageCompression(Imagick::COMPRESSION_JPEG);
  $thumb->setImageCompressionQuality(10);
  $thumb->resizeImage(50,0,Imagick::FILTER_LANCZOS,1);
  $thumb->setImageFormat('jpeg');
  file_put_contents ("lib/img/plakate/preview/{$key}.jpg", $thumb);
  $thumb->destroy();

}

As I see everything works fine – only the file extension is missing. :(


Solution

  • Your code $key = basename($img,'.jpg').PHP_EOL; has a PHP_EOL at the end, saying that the line ends here, "discarding" anything after it when assembling your filename.

    Change $key = basename($img,'.jpg').PHP_EOL; to $key = basename($img,'.jpg'); to have your file extension appended.