2012-12-20 27 views
3

是否可以使用任何* nix程序,如'find'或Python,PHP或Ruby等脚本语言,它们可以搜索您的HDD并找到所有图像有相同的宽度和高度,又名方形尺寸?找到所有具有正方形尺寸的图像(比例为1:1)

+1

什么样的图像,文件命令会告诉你PNG和GIF的尺寸 – technosaurus

+0

jpgs和pngs。但是,如何返回'文件'中的维度并能够比较两者,然后只返回文件名(如果它们相同)? – bafromca

+1

沿着'find'的一些东西。 -type f | xargs -I {} sh -c'res = \'identify -format“%w - %h”{} 2> |/dev/null \';如果[-n“$ res”] && [\'echo $ res | bc''-eq 0];然后echo {}; fi''用于缓慢的方法和ImageMagick支持的任何类型的图像。 – mmgp

回答

5

这对Python来说肯定是可行的。

您可以使用os.walk遍历文件系统,并使用PIL来检查图像是否在两个方向上具有相同的尺寸。

import os, Image 

for root, dir, file in os.walk('/'): 
    filename = os.path.join(root, file) 
    try: 
     im = Image.open(filename) 
    except IOError: 
     continue 

    if im.size[0] == im.size[1]: 
     print filename 
6

下面的代码将递归列出指定路径下的文件,所以它可以看看所有的子文件夹的特定的硬盘上,你提到的。它还会根据您可以指定的一组文件扩展名来检查文件是否作为图像。然后它将打印具有匹配宽度和高度的任何图像的文件名和宽度,高度。当您调用脚本时,您可以指定您要在其下搜索的路径。下面显示了一个示例用法。

listimages.py

import PIL.Image, fnmatch, os, sys 

EXTENSIONS = ['.jpg', '.bmp'] 

def list_files(path, extensions): 
    for root, dirnames, filenames in os.walk(path): 
     for file in filenames: 
      if os.path.splitext(file)[1].lower() in extensions: 
       yield os.path.join(root, file) 

for file in list_files(sys.argv[1], EXTENSIONS): 
    width, height = PIL.Image.open(file).size 
    if width == height: 
     print "found %s %sx%s" % (file, width, height) 

使用

# listimages.py /home/user/myimages/ 
found ./b.jpg 50x50 
found ./a.jpg 340x340 
found ./c.bmp 50x50 
found ./d.BMP 50x50 
+0

如果有人没有用正确的扩展名命名他们的文件会怎么样? – mmgp

+0

@mmgp如果这是一个问题,那么你可以像迈克尔戴维斯在他的回答中那样做,并检查所有文件并尝试,除非它失败,从而忽略文件扩展名。但是这会慢得多,因为它会打开并读取计算机上的每个文件,而不是只有具有图像扩展名的文件。 –

2

bash您可以通过使用像这样得到的图像大小:

identify -verbose jpg.jpg | awk '/Geometry/{print($2)}' 

又读man findman identify

+3

使用标识,你可以通过使用'identify -format“%w,%h”'来删除awk部分,但是他仍然需要比较这些值 – iagreen

2

这可以在一个shell行中完成,但我不建议这样做。分两步做。首先,收集文件中的所有图像文件和需要的属性:

find . -type f -print0 | xargs -J fname -0 -P 4 identify \ 
    -format "%w,%h,%m,\"%i\"\n" fname 2>|/dev/null | sed '/^$/d' > image_list 

sed在那里只是为了去除所产生的空行。您可能需要为您的系统调整参数-P 4xargs。这里使用了ImageMagick的identify,因为它可以识别很多格式。这将创建一个名为image_list的文件,它是一种典型的CSV格式。

现在,它只是根据您的需要筛选image_list的问题。为此,我更喜欢使用Python为:

import sys 
import csv 

EXT = ['JPEG', 'PNG'] 

for width, height, fformat, name in csv.reader(open(sys.argv[1])): 
    if int(width) == int(height) and width: 
     # Show images with square dimensions, and discard 
     # those with width 0 
     if fformat in EXT: 
      print name 

这个答案的第一部分可以在Python中轻易改写的,但因为它要么涉及使用ImageMagick的绑定Python或调用它通过subprocess,我离开它作为shell命令的组合。

相关问题