I want to crop an image using command line tools only indicating pixels to crop for the four directions (the same way we can crop in LibreOffice)
For example:
crop image.jpg -top 5px -bottom 7px -right 14px -left 3px
Is there such a tool (not GUI)?
Here is a workaround using
convert
from image magick pack.For a picture
image.jpg
As shown above, the input image is 720x482px.
Now to do cropping you have to determine two factors:
Now back to the image
image.jpg
above, I want to crop:then you could do it with (
width
xheight
+left
+top
/w
xh
+l
+t
format):Now
If you want to trim white regions away,
imagemagick
has a special command for it:To create a "user friendly" cli- option, the script below can be used. Simply run the command:
It creates a cropped image of
image.jpeg
, namedimage[cropped].jpeg
in the same directory.The script
How to use
The script uses
imagemagick
Save the script above as
crop_image
(no extension) in~/bin
.source ~/.profile
to make the directory show up in$PATH
.Now simply run the script by its name, as mentioned, e.g.:
Spaces are no problem, as long as in that case, you use quotes:
Use
mogrify -crop <W>x<H>+<X>+<Y> <files>
.Careful: the files are overwritten without notice. Add the
-path
option to specify an output directory to prevent this if required.As an example:
mogrify -crop 256x256+10+5 images/*.jpg
will crop each image in theimages
folder to a 256x256 image by starting 10 pixels from the top and 5 pixels from the side. It will overwrite the old images.If you get a
Argument list too long
error due to trying to convert many images at once, simply wrap your image path in single quotes to prevent bash from expanding it:mogrify -crop 256x256+10+5 'images/*.jpg'
(mogrify will do the expansion itself)The
crop
command needs 4 things. To understand it take the image you want to crop. Now, imagine that on the image, you are drawing a rectangle of the size which you want to retain. The area outside this rectangle will be eliminated, cropped. The rectangle must not be tilted i.e. the top side must be horizontal.Now, note down these 4 things:
Thus you have now W, H, L and T values. So far so good. To know the pixels, you may install krule tool in Ubuntu. Very useful.
Now, open the terminal and go to the folder where the image is stored. Use the following command and put the values of W, H, L and T properly:
You can use convert command in
image magick
pack.To install
sudo apt-get install imagemagick
orsudo yum install ImageMagick
.Then use
-crop geometry
to crop the image. For more readings read here