libcmark contains an API that allows you to modify elements of the syntax tree fairly easily. For example, you could iterate over the tree and convert all image URLs in the way you describe, before passing it to the HTML renderer.
The same sort of thing is possible in the JS implementation. At this point we haven’t provided a convenience function for iterating over all elements in the tree, but that’s something I mean to do at some point.
I have also built an experimental version of cmark that integrates lua and allows you to define custom writers and tree transformers in lua. It’s not in a completely useable state yet, but I’ll revisit it later.