twainscan.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. #!-*-coding:utf-8 -*-
  2. import twain
  3. import traceback
  4. import uuid
  5. import sys,os
  6. import locale
  7. import SocketServer
  8. import BaseHTTPServer
  9. import re
  10. import json
  11. from Queue import Queue
  12. from threading import Thread
  13. from multiprocessing import Process
  14. reload(sys)
  15. sys.setdefaultencoding("utf-8")
  16. root = "c:\\AppData\\Xscanner"
  17. xqueue = Queue()
  18. class XHttpHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  19. """
  20. """
  21. def do_HEAD(self):
  22. """Serve a HEAD request."""
  23. self.send_response(200)
  24. self.send_header("Access-Control-Allow-Origin","*")
  25. self.send_header("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE,HEAD")
  26. self.send_header("Access-Control-Allow-Headers","x-requested-with,content-type")
  27. self.send_header("Content-Type","application/json;charset=UTF-8")
  28. self.end_headers()
  29. def read_local_file(self,path):
  30. f = open(path,'rb')
  31. read = f.read()
  32. f.close()
  33. #print path
  34. return read
  35. def send_response(self, code, message=None):
  36. """Send the response header and log the response code.
  37. Also send two standard headers with the server software
  38. version and the current date.
  39. """
  40. self.log_request(code)
  41. if message is None:
  42. if code in self.responses:
  43. message = self.responses[code][0]
  44. else:
  45. message = ''
  46. if self.request_version != 'HTTP/0.9':
  47. self.wfile.write("%s %d %s\r\n" %
  48. (self.protocol_version, code, message))
  49. self.send_header('Date', self.date_time_string())
  50. def do_GET(self):
  51. """
  52. """
  53. if self.path.split("?")[0] == '/xscanAction.aspx':
  54. print self.path
  55. try:
  56. id = int(re.search(r"tid=(.*)",self.path).groups()[0])
  57. except Exception as e:
  58. id = None
  59. print e
  60. if id:
  61. t = Thread(target = start_scan)
  62. t.start()
  63. self.send_response(200)
  64. self.send_header("Content-Type","text/html;charset=UTF-8")
  65. self.end_headers()
  66. self.wfile.write("success")
  67. if self.path.split("?")[0] == '/xscanSourceList.aspx':
  68. snames = get_source_names()
  69. self.send_response(200)
  70. self.send_header("Access-Control-Allow-Origin","*")
  71. self.send_header("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE")
  72. self.send_header("Access-Control-Allow-Headers","x-requested-with,content-type")
  73. self.send_header("Content-Type","application/json;charset=UTF-8")
  74. self.end_headers()
  75. self.wfile.write(json.dumps(snames))
  76. if self.path.split("?")[0] == '/xscanImgUri.aspx':
  77. imgs = []
  78. while True:
  79. if not xqueue.empty():
  80. imgs.append(xqueue.get(block=False))
  81. continue
  82. break
  83. img = ",".join(imgs)
  84. self.send_response(200)
  85. self.send_header("Access-Control-Allow-Origin","*")
  86. self.send_header("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE")
  87. self.send_header("Access-Control-Allow-Headers","x-requested-with,content-type")
  88. self.send_header("Content-Type","application/json;charset=UTF-8")
  89. self.end_headers()
  90. self.wfile.write(img)
  91. if self.path.split("?")[0] == '/xscanImgReview.aspx':
  92. try:
  93. imgid = re.search(r"imgid=(.*)",self.path).groups()[0]
  94. except Exception as e:
  95. imgid = None
  96. print e
  97. imgpath = os.path.join(root,imgid)
  98. content = self.read_local_file(imgpath)
  99. self.send_response(200)
  100. self.send_header("Access-Control-Allow-Origin","*")
  101. self.send_header("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE")
  102. self.send_header("Access-Control-Allow-Headers","x-requested-with,content-type")
  103. self.send_header("Content-Type","image/png")
  104. #self.send_header("Content-Type","application/json;charset=UTF-8")
  105. self.end_headers()
  106. self.wfile.write(content)
  107. if self.path == '/':
  108. self.path = "index.html"
  109. def server():
  110. try:
  111. addr = len(sys.argv) < 2 and "localhost" or sys.argv[1]
  112. port = len(sys.argv) < 3 and 19882 or locale.atoi(sys.argv[2])
  113. handler = XHttpHandler
  114. httpd = SocketServer.TCPServer((addr, port), handler)
  115. print ("HTTP server is at: http://%s:%d/" % (addr, port))
  116. httpd.serve_forever()
  117. except KeyboardInterrupt:
  118. sys.exit()
  119. def get_source_names():
  120. """
  121. """
  122. sm = twain.SourceManager(0)
  123. return sm.GetSourceList()
  124. def start_scan():
  125. try:
  126. sm = twain.SourceManager(0)
  127. ss = sm.OpenSource("AT360")
  128. ss.RequestAcquire(0,0)
  129. try:
  130. if not os.path.exists(root):
  131. os.makedirs(root)
  132. while True:
  133. try:
  134. rv = ss.XferImageNatively()
  135. if rv is None:
  136. break
  137. else:
  138. (handle, count) = rv
  139. imgname = '{}.png'.format(uuid.uuid4())
  140. imgfile = os.path.join(root,imgname)
  141. twain.DIBToBMFile(handle, imgfile)
  142. xqueue.put(imgname)
  143. except:
  144. traceback.print_exc()
  145. break
  146. except:
  147. traceback.print_exc()
  148. print "Error!"
  149. except Exception:
  150. return False,u"找不到扫描仪!"
  151. if __name__ == "__main__":
  152. server()