Hook to get image filename when it is uploaded

I want to get the full local filename of an uploaded image so that I can copy it to a new directory and process it with my own image processing scripts. Which hooks/actions should I look into to achieve this?


Solutions Collecting From Web of "Hook to get image filename when it is uploaded"

The handle_upload hook is called after wp_handle_upload is run, and it sends in a named array consisting of ‘file’, ‘url’ & ‘type’. You could possibly use code like this to utilise it, depending on what you need to achieve:

function process_images($results) {
    if( $results['type'] === 'image/jpeg' ) { // or /png or /tif / /whatever
        $filename = $results[ 'file' ];
        $url = $results[ 'url' ];

        // manipulate the image

add_action('wp_handle_upload', 'process_images');

Edit: If you need the attachment ID as well, it might be better hooking in at a higher level, such as add / edit attachment:

add_action('add_attachment', 'process_images');
add_action('edit_attachment', 'process_images');

in which case the variable sent in is the attachment_id, from which you can derive the rest using something like:

$metadata = wp_get_attachment_metadata( $results );

If you want the filename, and not just the path relative to the root of the file, you must add this line of code:

$filename = substr($results['file'], ( strrpos($results['file'], '/', -1) + 1 ) ); //add +1 to remove the slash at the beginning 

EDIT: Just after posting this strrpos() solution, I found a best one:

$filename = basename($results['url']);