图像缩略图

您可以使用matplotlib从现有图像生成缩略图。matplotlib本身支持输入端的PNG文件,如果安装了PIL,则透明地支持其他图像类型。

  1. # build thumbnails of all images in a directory
  2. import sys
  3. import os
  4. import glob
  5. import matplotlib.image as image
  6. if len(sys.argv) != 2:
  7. print('Usage: python %s IMAGEDIR' % __file__)
  8. raise SystemExit
  9. indir = sys.argv[1]
  10. if not os.path.isdir(indir):
  11. print('Could not find input directory "%s"' % indir)
  12. raise SystemExit
  13. outdir = 'thumbs'
  14. if not os.path.exists(outdir):
  15. os.makedirs(outdir)
  16. for fname in glob.glob(os.path.join(indir, '*.png')):
  17. basedir, basename = os.path.split(fname)
  18. outfile = os.path.join(outdir, basename)
  19. fig = image.thumbnail(fname, outfile, scale=0.15)
  20. print('saved thumbnail of %s to %s' % (fname, outfile))

下载这个示例