imagemagickpng

How to avoid ImageMagick generating caNv chunk in PNG output?


I'm using ImageMagick command-line to preprocess some images that used as InstallBuilder's resource. The images are cropped to conform with size limit:

$ convert input.png -crop 163x314 output.png

However, the result PNG file always contains an new chunk named caNv:

$ pngcheck -v output-0.png
......
chunk caNv at offset 0x00086, length 16
unknown private, ancillary, safe-to-copy chunk
......

This chunk is unknown to InstallBuilder and causes the output installer crash. What does the chunk contains? How to avoid ImageMagick producing this chunk? Or is there a simple command-line that can remove it?


Solution

  • ImageMagick uses that to "remember" where your crop originated from in the canvas of the input image. If you don't need it, you can repage the cropped image which tells it to forget where it came from:

    magick input.png -crop 163x314 +repage output.png
    

    I can demonstrate that by creating a 110x110 image and cropping part of it, then checking what I got. Then doing it again, but with repaging:

    # Create 110x110 image to play with
    magick -size 110x110 xc: a.png
    

    First crop without repage

    magick a.png -crop 100x100+0+0 b.png
    identify b.png
    b.png PNG 100x100 110x110+0+0 8-bit Gray 2c 353B 0.000u 0:00.000  # Note 110x110+0+0, which *"remembers"* where it came from
    
    # Confirm that caNv chunk is present
    pngcheck -v b.png | grep caNv
    

    Output

    chunk caNv at offset 0x00072, length 16  
    

    Crop again, but with repaging this time

    magick a.png -crop 100x100+0+0 +repage b.png
    identify b.png
    b.png PNG 100x100 100x100+0+0 8-bit Gray 2c 325B 0.000u 0:00.000   # ImageMagick has forgotten and now believes 100x100 is the full story  
    
    # Confirm that caNv chunk is absent
    pngcheck -v b.png | grep caNv           # prints nothing
    

    Note that your crop command tells ImageMagick to cut the image into chunkS (plural) of size 163x314 and that is why you get 4 output files, output-0.png through output-3.png. If you want just the first chunk, from the top-left, saved as output.png without numeric identifier, use a specific offset with your crop:

    magick input.png -crop 163x314+0+0 +repage output.png
    

    If you want your chunk from the bottom-right corner, use:

    magick input.png -gravity SouthEast -crop 163x314+0+0 output.png
    

    You can set gravity to any of the 8 points of a compass, or center.