Search code examples
pythonimagemagickcropimagemagick-convertwand

convert and crop image in tiles with python


I tried to tile a JPG image in python. Usualy I use imageMagick .. so I have seen than wand seems to do this work ...

But I am not able to translate

 convert -crop 256x256 +repage big_image.jpg tiles_%d.jpg

someone ca help me ?


Solution

  • Python's wand library offers a unique crop alternative. Using wand.image.Image[left:right, top:bottom] can sub-slice a new virtual pixel image.

    from wand.image import Image
    
    with Image(filename="big_image.jpg") as img:
    i = 0
    for h in range(0, img.height, 256):
        for w in range(0, img.width, 256):
            w_end = w + 256
            h_end = h + 256
            with img[w:w_end, h:h_end] as chunk:
                chunk.save(filename='tiles_{0}.jpg'.format(i))
            i += 1
    

    The above will generate many tile images that match the +repage option from:

    convert -crop 256x256 +repage big_image.jpg tiles_%d.jpg