📄 assemble_images.py
字号:
#!/usr/bin/env pythonimport sysimport osimport getoptimport tempfileimport PIL.Imagedef imconcatlr(left, right): # concatenate left and right images w1, h1 = left.size w2, h2 = right.size print >> sys.stderr, "lr:", (w1, h1), "+", (w2, h2) result = PIL.Image.new("RGB", (w1+w2, h1)) result.paste(left, (0, 0)) result.paste(right, (w1, 0)) return resultdef imconcattb(upper, lower): # concatenate upper and lower images w1, h1 = upper.size w2, h2 = lower.size print >> sys.stderr, "tb:", (w1, h1), "+", (w2, h2) result = PIL.Image.new("RGB", (w1, h1+h2)) result.paste(upper, (0, 0)) result.paste(lower, (0, h1)) return resultdef pnmsize(pnmfile): f = open(pnmfile) line1 = f.readline() line2 = f.readline() w, h = [int(n) for n in line2.split()] return w, hdef main(args): opts, args = getopt.getopt(args, "n") do_netpbm = False for opt, arg in opts: if opt == "-n": do_netpbm = True if do_netpbm: netpbm_assemble_images(args) else: pil_assemble_images(args)def netpbm_assemble_images(files): rows = [] n = 1 for f in files: w, h = pnmsize(f) if not rows: print >> sys.stderr, "first image:", (w, h) rows.append([f]) elif pnmsize(rows[-1][-1])[1] != h: # height differs - start a new row print >> sys.stderr, "last image:", pnmsize(rows[-1][-1]), print >> sys.stderr, "new image:", (w, h), "==> new row" rows.append([f]) else: # append to current row print >> sys.stderr, "last image:", pnmsize(rows[-1][-1]), print >> sys.stderr, "new image:", (w, h), "==> same row" rows[-1].append(f) for (i, row) in enumerate(rows): if len(row) > 1: fd, pnmfile = tempfile.mkstemp() os.close(fd) os.system("pnmcat -lr %s > %s 2>/dev/null" % (" ".join(row), pnmfile)) for f in row: os.unlink(f) rows[i] = pnmfile else: rows[i] = row[0] fd, pnmfile = tempfile.mkstemp() os.close(fd) os.system("pnmcat -tb %s > %s 2>/dev/null" % (" ".join(rows), pnmfile)) for f in rows: os.unlink(f) os.system("pnmtopng %s 2>/dev/null" % pnmfile) os.unlink(pnmfile)def pil_assemble_images(files): rows = [] n = 1 for f in files: image = PIL.Image.open(open(f, "rb")) image.save(open("%d.png" % n, "wb"), "PNG") n += 1 if not rows: # first image print >> sys.stderr, "first image:", image.size rows.append(image) elif image.size[1] != rows[-1].size[1]: # height differs - start a new row print >> sys.stderr, "last image:", rows[-1].size, print >> sys.stderr, "new image:", image.size, "==> new row" rows.append(image) else: # append to current row print >> sys.stderr, "last image:", rows[-1].size, print >> sys.stderr, "new image:", image.size, "==> same row" rows[-1] = imconcatlr(rows[-1], image) # now concatenate the result top-to-bottom full_image, rows = rows[0], rows[1:] for image in rows: full_image = imconcattb(full_image, image) full_image.save(sys.stdout, "PNG")if __name__ == "__main__": main(sys.argv[1:])
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -