Custom preview for macros

Confluence uses a custom preview by inserting an image for some of their own macros.
Is there a way or an api to do this with my own macros?

I could create a servlet that generates an image preview, even though I’d just like it to be the actual output of the macro, but the image is fine for now.
However, how do I tell the macro to display as that image? I could use javascript to replace all src attributes of my macros with my custom preview but that doesn’t seem right.

Is there a better way?

You can use Macro’s ConversionContext to determine if request is for Display or Preview and generate custom preview when necessary.

private boolean isPreview(ConversionContext context) {
    return ConversionContextOutputType.PREVIEW.value()

Something like above method in your Macro class can help you.