How to keep spam off wordpress image attachments by not allowing comments on them

How to keep spam off wordpress image attachments by not allowing comments on them.

Place the following in your theme’s functions.php file.

add_filter( 'comments_open', 'no_media_comments', 10, 2 );

function no_media_comments( $open, $post_id ) {

	$post = get_post( $post_id );
        // wordpress refers to images as attachments
	if ( 'attachment' == $post->post_type )
		$open = false;

	return $open;
}