Search code examples
imagemagickimagemagick-convert

Compose multiple regions of an image into a target


I'm trying to use ImageMagick to compose different pieces of a rendered PDF into a target. E.g., I want to have ImageMagick render the PDF at 300dpi, then create a 300x400 pixel output image, then take from the PDF the area 10x20+30+40 and place it in the target (300x400 pixel image) at 12,34. Then take another (and a third and fourth) chunk at different coordinates with different sizes and place them at different places.

I cannot seem to figure out how to do this in one go, and doing it in multiple runs always re-renders the PDF and takes awfully long. Is this even possible?


Solution

  • Here's an idea of how you can approach this. It uses the MPR or "Memory Program Register" that Fred suggested in the comments. It is basically a named chunk of memory that I write into at the start and which I recall later when I need it.

    Here is a rather wonderful start image from the Prokudin-Gorskii collection:

    enter image description here

    The code resizes the image and saves a copy in the MPR. Then, takes a copy of the MPR, crops out a head, resizes it and composites the resized result onto the resized original at a different location and then repeats the process for another head.

    magick Prokudin.png -resize 300x400\! -write MPR:orig \
        \( MPR:orig -crop 50x50+180+84 -resize 140x140  \) -geometry +10+240 -compose src-over -composite \
        \( MPR:orig -crop 40x40+154+184                 \) -geometry +40+100 -compose src-over -composite \
        result.png
    

    enter image description here

    If you have trouble understanding it, try running it with the second or third line omitted so it just does one head ;-)

    Hopefully it covers all the aspects of your question and you can adapt it to your PDF.