Check if the image exists in WordPress media library

Look, as far I understood, the thing you are asking can be done primarily two ways-

First is to go through the uploads directory recursively and search for the file with filename and type. If the file is found then copy it form there and then no need to download it. But it’s very costly regarding the resource and power it’ll use. Of course you can implement it, but the solution is kinda long to answer here at this field. The main idea for the recursive searching is, there are libraries for PHP by which you can list the files of a directory recursively and check if your file is there or not.

Second is the WP way, which will not be that helpful for your condition I think. It’ll just check if the image is registered in the DB or not. The function code is here-

/**
 * If the image file is there.
 *
 * @param string $img The image name with extension after dot.
 *
 * @return bool|int
 */
function codemascot_if_the_image_is_there( $img ) {
    global $wpdb;
    $img = '%/' . $img;
    $sql = $wpdb->prepare(
        "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
        $img
    );
    return $wpdb->get_var( $sql ) !== null ? $wpdb->get_var( $sql ) : false;
}

Use this function like codemascot_if_the_image_is_there('test.jpg'). It’ll give you a post ID or false based on the query it runs. For your case pass the $filename as the parameter. If the file is inside you’ll get an integer otherwise false. If you get an integer then I prefer no need to copy. You can directly attach it to a post. This will save you some space in your server.

Hope this above answer helps.

NB: I haven’t tested the function code. Please test it before putting it to production. Better give a feedback here at comments.