#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- mode: python;Encoding: utf8n -*- u""" 画像に変な暗号化をかけてみるPythonスクリプト PIL(Pillow)を使用。 Usage: python imgcrypt.py IN_IMAGE OUT_IMAGE """ import sys import os from PIL import Image next = 1 def rand(): u"""乱数生成器(C言語のソレ)""" global next next = (next * 1103515245 + 12345) & 0xffffffff return int((next / 65536) % 32768) def srand(seed): u"""乱数初期化。種を渡す。""" global next next = seed def encrypt_image(img): u"""画像を難読化。Imageを渡す。""" outimg = img.copy() w, h = img.size srand(0) for y in range(h): rx = rand() for x in range(w): c = img.getpixel(((x + rx) % w, y)) outimg.putpixel((x, y), c) return outimg def decrypt_image(img): u"""画像の難読化の解除。Imageを渡す。""" outimg = img.copy() w, h = img.size srand(0) for y in range(h): rx = rand() for x in range(w): c = img.getpixel(((x - rx) % w, y)) outimg.putpixel((x, y), c) return outimg def main(): if len(sys.argv) < 3: print "Usage: python %s IN_IMAGE OUT_IMAGE" % \ os.path.basename( __file__ ) sys.exit() inimgfn = sys.argv[1] if not os.path.isfile(inimgfn): print "Not Found %s" % inimgfn sys.exit() outimgfn = sys.argv[2] img = Image.open(inimgfn, "r") outimg = encrypt_image(img) if True: # 画像を保存 outimg.save(outimgfn) print "Output %s" % outimgfn else: # 画像を表示して確認 outimg.show() decrypt_image(outimg).show() if __name__ == '__main__': main()