The way to do it - and it is the way the PNG exporting plug-in itself does it internally - is to create an internal duplicate of the image before flattening it. To do it, just call gimp-image-duplicate
, and apply merge-visible-layers and file-*-save on the image copy returned by that call.
After saving, delete the newly created image with gimp-image-delete - else the duplicate will continue exiting in memory, with no displays associated (i.e. without showing on the graphical interface at all).
This copy may seem "expensive" in memory and CPU terms,but it is not at all: GIMP keeps references to the underlying pixels of the original image, until those are changed - the only change that is made, in this case, is the call do merge-layers, which then creates a new layer which would have to be created anyway.