Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
The problem is that -flatten is a 'image layering' operation. It obeys the virtual canvas and offset of the image. In this case the virual canvas is the same size as the original image, but the image also has an offset pushing the image off to one side.
In other words the image is not contained by the virtual canvas!
The +repage removes (resets) the virtual canvas size and offset, so that the virtual canvas matches the image, without any offset.
An alternative that will do the same thing is -layers TrimBounds though like other layer image operators it trims the bounds to match multiple images. But for one image, it is the same result. WARNING: it is not the same as -trim, as it does not look at the actual image contents.
Using -mosaic layering command would expand the virtual canvas so as to ensure the image is contained within the canvas but without changing its offset (in positive directions only as a virtual canvas is purely a size starting at +0+0 by definition).
And finally the -layers merge would fill in the background, but keep the images virtual offset position, It will also fix the canvas size appropriately. With one image it would just 'fill out the background' only.
One final possibility is -border 0 which will use border color to fill in the background, and not change anything else at all! It will not even 'flatten' multiple images into a single image, which all the other layering operators will do.