Advertisement
Guest User

gif_qr.py

a guest
May 25th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.11 KB | None | 0 0
  1. #!/usr/bin/python2
  2.  
  3. import os
  4. import qrtools
  5. import sys
  6. from PIL import Image
  7.  
  8. __author__ = "Maki from _PRIME_"
  9. __version__ = "1.0"
  10.  
  11.  
  12. def analyseImage(path):
  13.     '''
  14.    Pre-process pass over the image to determine the mode (full or additive).
  15.    Necessary as assessing single frames isn't reliable. Need to know the mode
  16.    before processing all frames.
  17.  
  18.    @param path: path to GIF file
  19.  
  20.    @type path: C{GIF}
  21.  
  22.    @raise path: Check if the file exists
  23.  
  24.    @return: This function returns a dictionnary that contains the image files.
  25.    '''
  26.     try:
  27.         im = Image.open(path)
  28.         results = {
  29.             'size': im.size,
  30.             'mode': 'full',
  31.         }
  32.         try:
  33.             while True:
  34.                 if im.tile:
  35.                     tile = im.tile[0]
  36.                     update_region = tile[1]
  37.                     update_region_dimensions = update_region[2:]
  38.                     if update_region_dimensions != im.size:
  39.                         results['mode'] = 'partial'
  40.                         break
  41.                 im.seek(im.tell() + 1)
  42.         except EOFError:
  43.             pass
  44.  
  45.         return results
  46.     except IOError:
  47.         print("Wrong file name")
  48.  
  49.  
  50. def processImage(path):
  51.     '''
  52.    Iterate the GIF, extracting each frame and decode qr code on
  53.    each extracted file.
  54.  
  55.    @param path: Path to GIF file
  56.  
  57.    @type path: C{GIF}
  58.  
  59.    @raise path: Check the file type
  60.    @raise path: Check for end of file
  61.  
  62.    @return: This function returns nothing, it just write
  63.    each frame of the GIF as a PNG file on disk.
  64.    '''
  65.     try:
  66.         mode = analyseImage(path)['mode']
  67.         flag = []
  68.  
  69.         im = Image.open(path)
  70.  
  71.         i = 0
  72.         p = im.getpalette()
  73.         last_frame = im.convert('RGBA')
  74.  
  75.         try:
  76.             while True:
  77.                 # You can uncomment the line below to get more verbosity
  78.                 # print("saving {0} ({1}) frame {2}, {3} {4}".format(path, mode, i, im.size, im.tile))
  79.                 # If the GIF uses local colour tables, each frame will
  80.                 # have its own palette.
  81.                 # If not, we need to apply the global palette to the new frame.
  82.                 if not im.getpalette():
  83.                     im.putpalette(p)
  84.  
  85.                 new_frame = Image.new('RGBA', im.size)
  86.  
  87.                 # Is this file a "partial"-mode GIF where frames
  88.                 # update a region of a different size to the entire image?
  89.                 # If so, we need to construct the new frame by pasting
  90.                 # it on top of the preceding frames.
  91.                 if mode == 'partial':
  92.                     new_frame.paste(last_frame)
  93.  
  94.                 # Will set frame name, example : if toto.gif in
  95.                 # input then toto-0.png, toto-1.png etc...
  96.                 png_file = '%s-%d.png' % (''.join(os.path.basename(path).split('.')[:-1]), i)
  97.                 new_frame.paste(im, (0, 0), im.convert('RGBA'))
  98.                 new_frame.save(png_file, 'PNG')
  99.  
  100.                 # QR Code decoder
  101.                 qr = qrtools.QR()
  102.                 qr.decode(png_file)
  103.                 flag.append(qr.data)
  104.  
  105.                 print(''.join(flag))
  106.  
  107.                 i += 1
  108.                 last_frame = new_frame
  109.                 im.seek(im.tell() + 1)
  110.         except EOFError:
  111.             pass
  112.  
  113.     except TypeError:
  114.         print("Wrong file type")
  115.  
  116.  
  117. def cleanDir():
  118.     '''
  119.    Directory cleaner, this function will delete all png file in
  120.    the current directory.
  121.    '''
  122.     filelist = [f for f in os.listdir(".") if f.endswith(".png")]
  123.     for f in filelist:
  124.         os.remove(f)
  125.  
  126.  
  127. def showHelp():
  128.     print("\
  129.    This script will split a GIF File in frames and decode the QR Code inside it. \n \
  130.    Frames will be stored in the current folder as png files and delete with the cleanDir function.\n  \
  131.    \n \
  132.    Usage: gif_qr.py <file.gif> \
  133.    ")
  134.  
  135. if __name__ == "__main__":
  136.     if len(sys.argv) > 1:
  137.         gif_file = sys.argv[1]
  138.         processImage(gif_file)
  139.         # Comment the function below to keep PNG file
  140.         cleanDir()
  141.     else:
  142.         showHelp()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement