twainscan.py 5.9 KB

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