仅使用命令行工具裁剪图像

我想在我的CLI上仅使用命令行工具裁剪Ubuntu上的图像, 指示要为四个方向裁剪的像素。 (与libreoffice中的相同)

例如:

crop image.jpg -top 5px -bottom 7px -right 14px -left 3px 

有没有这样的工具(不是GUI)?

这是一个使用图像magick包convert的解决方法。

 sudo apt-get install imagemagick 

对于图片image.jpg

 $ identify image.jpg image.jpg JPEG 720x482 720x482+0+0 8-bit DirectClass 100KB 0.000u 0:00.009 

如上所示,输入图像为720x482px。

现在做裁剪你必须确定两个因素:

  1. 裁剪的起点(包括2个方向)
  2. 裁剪的矩形尺寸(此处可以包含其他方向)

现在回到上面的图像image.jpg ,我想裁剪顶部5px -bottom 7px -right 14px -left 3px然后你可以做到:

 convert image.jpg -crop 713x470+5+3 output.jpg 

现在

 $ identify output.jpg output.jpg JPEG 713x470 713x470+0+0 8-bit DirectClass 102KB 0.000u 0:00.000 

要创建“用户友好”的cli选项,可以使用下面的脚本。 只需运行命令:

  

它会创建一个image.jpeg的裁剪图像,在同一目录中命名为image[cropped].jpeg

剧本

 #!/usr/bin/env python3 import subprocess import sys # image, crop- dimensions img = sys.argv[1]; left = sys.argv[2]; right = sys.argv[3]; top = sys.argv[4]; bottom = sys.argv[5] # arrange the output file's name and path img_base = img[:img.rfind(".")]; extension = img[img.rfind("."):]; path = img[:img.rfind("/")] img_out = img_base+"[cropped]"+extension # get the current img' size data = subprocess.check_output(["identify", img]).decode("utf-8").strip().replace(img, "") size = [int(n) for n in data.replace(img, "").split()[1].split("x")] # calculate the command to resize w = str(size[0]-int(left)-int(right)); h = str(size[1]-int(top)-int(bottom)); x = left; y = top # execute the command cmd = ["convert", img, "-crop", w+"x"+h+"+"+x+"+"+y, "+repage", img_out] subprocess.Popen(cmd) 

如何使用

  1. 该脚本使用imagemagick

     sudo apt-get install imagemagick 
  2. 将上面的脚本保存为~/bin crop_image (无扩展名)。

  3. 必要时创建目录。 在这种情况下,还要运行source ~/.profile以使目录显示在$PATH
  4. 使脚本可执行。

现在只需按名称运行脚本,如上所述:

 crop_image /path/to/image.jpg 20 30 40 50 

空格没问题,只要在这种情况下,你使用引号:

 crop_image '/path/with spaces in the name/to/image.jpg' 20 30 40 50 

如果你想要修剪白色区域, imagemagick有一个特殊的命令:

 convert -trim input.jpg output.jpg 

您可以在image magick pack中使用convert命令。
要安装sudo apt-get install imagemagicksudo yum install ImageMagick
然后使用-crop geometry来裁剪图像。 有关更多读数,请阅读此处

使用mogrify -crop x++

小心:文件被覆盖,恕不另行通知。