Here comes the plugins to rescue, move that code into a plugin and activate. That’ll not change header image upon every theme change.
E.g –
<?php
/*
Plugin Name: keep header always
*/
// Your code to keep header image
?>
save it as whatever-foo.php
upload to /wp-content/plugins/
directory and activate it