title: When using PHP and ImageMagick to resize and name images recursively, how to best write new files based on the existing filename and extension
body: <p>I've got a directory of 'source' images that I'm saving out multiple resized files. I'd like all jpg and png files in a given directory to be resized and saved with new names based on their original file names (a la filename-small.jpg, filename-medium.jpg, etc.) I'm using ImageMagick.</p>
  <p>The regex stuff to get all the files was found in another question here on <a href="https://stackoverflow.com/questions/24980967/find-images-with-certain-extensions-recursively/24981012">SO</a> and has helped—but I don't totally get what all is going on here.</p>
  <p>What I have currently plops the original file extension in the middle of the file name. While I understand why this is happening, I'm not sure the best approach to fix this.</p>
  <p>How can I get this to to be <strong>filename-large.jpg</strong> instead of <strong>filename.jpg-large.jpg</strong>?</p>
  <p>Here is what I have currently:</p>
  <pre><code>&lt;?php
  
      $directory = new RecursiveDirectoryIterator('source/assets/uploads/test');
      $iterator = new RecursiveIteratorIterator($directory);
      $images = new RegexIterator($iterator, '/^.+(.jpe?g|.png)$/i', RecursiveRegexIterator::GET_MATCH);
  
      $widths = [
          'small' =&gt; 400,
          'medium' =&gt; 800,
          'large' =&gt; 1000,
          'xlarge' =&gt; 1600,
      ];
      
      foreach($images as $image =&gt; $value) {
  
          // Set the original filename w/o the extension
          $originalFilename = $image;
  
          // set the extension based on the original
          // ideally conform the extension jpeg to jpg
          $originalExtension = '.jpg';
          
          // create a new Imagick instance
          $newImage = new Imagick($image);
  
          // strip out some junk
          $newImage-&gt;stripImage();
  
          // write a new file for each width 
          // and name it based on the original filename
          foreach ($widths as $key =&gt; $value) {
              // using 0 in the second $arg will keep the same image ratio
              $newImage-&gt;resizeImage($value,0, imagick::FILTER_LANCZOS, 0.9);
              $newImage-&gt;writeImage($originalFilename . '-' . $key . $originalExtension);
          }
      }
  </code></pre>