How would I attach media/images to a post based on a ID stored in a each post’s custom field

wp_insert_attachment will insert an attachment post for a given parent post ID and filename. You can write a little script to query for all your posts with the legacy key, get their associated image paths, and call wp_insert_attachment for each.