Add a thumbnail subfolder to an image path
I got a question from one of my Codeigniter.tv users that comes up more often, so I thought I'd just post the answer here for the world to see.
Say I have an image path 'image_path/123.jpg' stored in my database and I need that image's thumbnail, which is in 'image_path/200x200/123.jpg'. Well, here's a little helper function to do just that.
Just pass the path and subfolder name to this helper function and it will insert the subfolder in the string.
I also posted it as a gist: https://gist.github.com/4671601
<?php function get_thumbnail($img_path, $folder = ''){ // Should we just return the given $img_path if(empty($folder) || !strstr($img_path, '/')){ return $img_path; } // Insert folder name before image filename $img_path = explode('/', $img_path); $file_name = array_pop($img_path); array_push($img_path, $folder); array_push($img_path, $file_name); return implode('/', $img_path); } echo get_thumbnail('/image_path/thumbs/12312.jpg', '200x200') . PHP_EOL; echo get_thumbnail('/image_path/thumbs/12312.jpg') . PHP_EOL; echo get_thumbnail('/som/other/path/test.jpg', 'folder/300') . PHP_EOL;