gif.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/bin/python3
  2. import socket
  3. import sys
  4. import random
  5. import time
  6. import math
  7. from PIL import Image
  8. im = Image.open("wave.gif")
  9. N_ROWS = 5
  10. N_COLS = 10
  11. oldPing = time.time()
  12. # Create a TCP/IP socket
  13. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  14. # Connect the socket to the port where the server is listening
  15. server_address = ('0.0.0.0', 2020)
  16. print('binding {} port {}'.format(*server_address))
  17. sock.bind(server_address)
  18. sock.settimeout(30)
  19. def getBytes(im):
  20. x = im.load()
  21. pixels = [0] * (N_ROWS * N_COLS)
  22. for row in range(N_ROWS):
  23. for col in range(N_COLS):
  24. pixels[row*N_COLS + col] = int(int(x[col, row]/16) + random.random() * (x[col, row]-int(x[col, row])))
  25. pixels[49] = int(pixels[49]/2)
  26. return bytes([0x41] + pixels)
  27. frames = []
  28. try:
  29. while 1:
  30. im.seek(im.tell()+1)
  31. im.thumbnail((N_COLS, N_ROWS), Image.ANTIALIAS)
  32. pixels = getBytes(im)
  33. frames.append(pixels)
  34. except EOFError:
  35. pass
  36. client_address = None
  37. frameIndex = 0
  38. print('frame count:', len(frames))
  39. if not frames:
  40. exit(1)
  41. try:
  42. while True:
  43. if not client_address:
  44. try:
  45. print('waiting...')
  46. data, addr = sock.recvfrom(16)
  47. print('received {} from {}'.format(data, addr))
  48. client_address = addr
  49. except socket.timeout:
  50. pass
  51. else:
  52. sock.sendto(frames[frameIndex], client_address)
  53. frameIndex = (frameIndex+1) % len(frames)
  54. if time.time() - oldPing > 30:
  55. try:
  56. data, addr = sock.recvfrom(16)
  57. print('received {} from {}'.format(data, addr))
  58. client_address = addr
  59. oldPing = time.time()
  60. except socket.timeout:
  61. client_address = None
  62. time.sleep(1/40)
  63. except KeyboardInterrupt:
  64. pass
  65. finally:
  66. print('closing socket')
  67. sock.close()