How to change images url in function.php?

Most of the cache plugins have built-in CDN settings. If you are looking for a simple solution for the image URL only, you can use CDN Enabler. It is from KeyCDN but you don’t have to use KeyCDN for it to work. Simply Write your alternative domain to only use image extensions if you don’t want to keep CSS, JS, etc in the subdomain.

If you want to do it by a filter, There are other works like creating an options panel so that you don’t have to hardcode the domain, etc.

CDN Enabler