How to crop images in batches

Process:

  • Create 2 folders (1 folder contains all the images to crop and the other is a empty folder)
  • Open this script in the Krita scripter
  • Edit the source_path and destination_path variables
  • Edit the crop dimensions
  • Run the script code

Code

# Import
import os
from PyQt5.QtCore import QDir, QRect
from PyQt5.QtGui import QImage, QImageReader


# Paths
source_path = "C:\\...\\folder\\source"
destination_path = "C:\\...\\folder\\destination"

# Clip
crop_left   = 7
crop_top    = 7
crop_width  = 512
crop_height = 657

# Files List
qdir = QDir( source_path )
qdir.setSorting( QDir.LocaleAware )
qdir.setFilter( QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot )
qdir.setNameFilters( [ "*.png", "*.jpg" ] )
files = qdir.entryInfoList()

# Loop Items
for i in range( 0, len( files ) ):
    # Paths
    image_path = os.path.normpath( files[i].filePath() )
    save_path = os.path.join( destination_path, os.path.basename( image_path ) )

    # Image
    qreader = QImageReader( image_path )
    if qreader.canRead() == True:
        qreader.setClipRect( QRect( crop_left, crop_top, crop_width, crop_height ) )
        qimage = qreader.read()
        qimage.save( save_path )
        del qimage
    del qreader

print( "Task End" )

Usually this problem happens to me where I have a lot of images to crop and today I had 6k images to crop. and must say this is going really FAST.

I have PyQt5 installed on my computer so I did not even use Krita to crop this I just ran this on my IDE but people can use scripter to call PyQt5 easy on Krita.

6 Likes

Would imagemagick be an alternative to this?

2 Likes

Yes, it can be done in ImageMagick too:

create two folders Input and Output and go to the directory where they are, for example i have both folders in my Pictures directory on a Win 11 system and ImageMagick 7.1.1.-12. The Input folder contains some png images. On the command line use change directory cd to get to the Pictures folder (or wherever Output and Input are) and type:

magick mogrify -path Output -crop 300x200+50+50 Input/*.png

The numbers after -crop are:

[width]x[height]+[x_offset]+[y_offset]

with the width and height of the cropped area that you want and the X- and Y-coordinate offsets from where the cropping should start. In the example i have set these values to 300, 200, 50 and 50. This worked on my system … ImageMagick is quite a useful tool to have.

2 Likes