You are manually constructing the image path, but Wordpress provides built-in function get_attached_file to do this.
str_replace( get_bloginfo('url'), ABSPATH, $attachment->guid ) can be changed to get_attached_file( $attachment->ID ) on lines 34 & 41.
Also, lines 42 & 43 are hardcoded to a specific number of subdirectories. You can use PHP's built-in function basename to get the filename from a path.