You can use get_post_galleries
to return an array of all the galleries in a post. The data returned includes all the image URLs and IDs, so take your pick of those to suit your case.
$galleries = get_post_galleries(
'', // assume current post, if not put a post ID here
false, // return an array of data rather than the gallery HTML
);
$images = explode(",",$galleries[0][ids]);
// use the first gallery. Traversing the array to collate all
// instances of [ids] is left as an exercise for the reader
$index = array_rand( $images );
$imageID = $images[$index];
// then do what you like with the image ID here
get_post_galleries
takes two parameters:
-
the customary optional
post ID
so you can either use it inside a loop or query any post. -
a boolean to indicate whether you want the whole gallery HTML (if true) or arrays of image IDs and URLs. The URLs are those of the image size specified for the gallery shortcode.