def multiScan(self): """ Scan and return an array of PIL objects If no images, will return an empty array """ if self.scanner == None: raise ScannerNotSet self.scanner.RequestAcquire(0, 1) # RequestAcquire(ShowUI, ShowModal) info = self.scanner.GetImageInfo() images = [] handles = [] try: handle, more = self.scanner.XferImageNatively() handles.append(handle) except twain.excDSTransferCancelled: return [] while more != 0: try: handle, more = self.scanner.XferImageNatively() handles.append(handle) except twain.excDSTransferCancelled: more = 0 for handle in handles: images.append(Image.open(StringIO(twain.DIBToBMFile(handle)))) twain.GlobalHandleFree(handle) return images
def capture(self): try: print("capture()") (handle, more_to_come) = self.scanner.XferImageNatively() except twain.excDSTransferCancelled: return None self.scannedImages.append( Image.open(StringIO(twain.DIBToBMFile(handle)))) twain.GlobalHandleFree(handle) return True
def capture(self): try: print("capture()") (handle, more_to_come) = self.scanner.XferImageNatively() except twain.excDSTransferCancelled: self.close() return None image = twain.DIBToBMFile(handle) twain.GlobalHandleFree(handle) return image
def scan(fullfilename = 'dg_pic.bmp', **kwargs): sm, scanner = open_scanner() try: adjust_scanner_properties(scanner, **kwargs) scanner.RequestAcquire(0, 0) # 1,1 to show scanner user interface (handle, more_to_come) = scanner.XferImageNatively() twain.DIBToBMFile(handle, fullfilename) twain.GlobalHandleFree(handle) finally: scanner.destroy() sm.destroy()
def scan(self): """Scan and return PIL object if success else return False """ self.scanner.RequestAcquire(0, 1) info = self.scanner.GetImageInfo() try: self.handle = self.scanner.XferImageNatively()[0] image = twain.DIBToBMFile(self.handle) twain.GlobalHandleFree(self.handle) return Image.open(StringIO(image)) except: return False
def scan(self, dpi=200): self._open(dpi) self._scanner.RequestAcquire(0, 0) info = self._scanner.GetImageInfo() if info: (handle, more_to_come) = self._scanner.XferImageNatively() str_image = twain.DIBToBMFile(handle) twain.GlobalHandleFree(handle) self._close() return Image.open(StringIO(str_image)) self._close() return None
def capture(self): fileName = "tmp.tmp" try: (handle, more_to_come) = self.source.XferImageNatively() except: return None twain.DIBToBMFile(handle, fileName) twain.GlobalHandleFree(handle) image = QImage(fileName) res = float(self.resolution) * 1000 / 25.4 image.setDotsPerMeterX(res) image.setDotsPerMeterY(res) return image
def _capture(ss): global index # sebagai nilai referensi apakah fungsi ini berjalan # dengan baik, dan sebagai referensi BREAK pada loop scan result = False try: rv = ss.XferImageNatively() fileName = str(index) + "_" + name_unique() + "_image.bmp" loc_file = folder_upload + fileName # untuk naming index saat looping # pengambilan gambar scan index += 1 if rv: (handle, count) = rv # simpan gambar kedalam file twain.DIBToBMFile(handle, loc_file) color = color.lower() if color == 'color': pass if color == 'gray': # convert to grayscale image = cv2.imread(loc_file) im_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imwrite(loc_file, im_gray) if color == 'black_white': # convert to grayscale image = cv2.imread(loc_file) im_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) (thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) cv2.imwrite(loc_file, im_bw) # encode to base64 imagebase64 = convert_to_base64(loc_file) # debug output print imagebase64 result = True except Exception as e: print str(e.message) return result
def single_scan_process(deviceId='', color='gray', capability=1): # create filename unique filename = name_unique() + ".bmp" # lokasi file loc_file = folder_upload + filename sm = twain.SourceManager(0) devices = sm.GetSourceList() ss = sm.OpenSource(devices[deviceId]) ss.RequestAcquire(0, 0) # set output pixel twain # ini berfungsi agar OCR bisa membaca lebih jelas # jika kurang dari 1500px maka tidak akan jelas if (capability == 2): ss.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32, 300.0) ss.SetCapability(twain.ICAP_XRESOLUTION, twain.TWTY_FIX32, 300.0) if (capability == 1): ss.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32, 200.0) ss.SetCapability(twain.ICAP_XRESOLUTION, twain.TWTY_FIX32, 200.0) if (capability == 0): ss.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32, 100.0) ss.SetCapability(twain.ICAP_XRESOLUTION, twain.TWTY_FIX32, 100.0) rv = ss.XferImageNatively() if rv: (handle, count) = rv twain.DIBToBMFile(handle, loc_file) color = color.lower() if color == 'color': pass if color == 'gray': # convert to grayscale image = cv2.imread(loc_file) im_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imwrite(loc_file, im_gray) if color == 'black_white': # convert to grayscale image = cv2.imread(loc_file) im_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) (thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) cv2.imwrite(loc_file, im_bw) # encode to base64 imagebase64 = convert_to_base64(loc_file) return [filename, imagebase64]
def ProcessXFer(self): """An image is ready at the scanner - fetch and display it""" more_to_come = False try: if self.XferMethod == XferNatively: XferFileName = tmpfilename (handle, more_to_come) = self.SD.XferImageNatively() twain.DIBToBMFile(handle, XferFileName) twain.GlobalHandleFree(handle) self.LogMessage(self.ProductName + ':' + 'Image acquired natively') else: try: XferFileName = 'TWAIN.TMP' # Default rv = self.SD.GetXferFileName() if rv: (XferFileName, type) = rv # Verify that the transfer file can be produced. Security # configurations on windows can prevent it working. try: self.VerifyCanWrite(XferFileName) except CannotWriteTransferFile: self.SD.SetXferFileName(OverrideXferFileName) XferFileName = OverrideXferFileName except: # Functionality to influence file name is not implemented. # The default is 'TWAIN.TMP' pass self.VerifyCanWrite(XferFileName) self.SD.XferImageByFile() self.LogMessage(self.ProductName + ':' + "Image acquired by file (%s)" % XferFileName) self.DisplayImage(XferFileName) if more_to_come: self.AcquirePending = True else: self.SD = None except: # Display information about the exception import sys, traceback ei = sys.exc_info() traceback.print_exception(ei[0], ei[1], ei[2])
def scan(destination_directory): Scanner.current_destination_directory = destination_directory try: while True: raw_file = Scanner.source.XferImageNatively() if raw_file: (handle, count) = raw_file new_file = os.path.join( destination_directory, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + ".bmp") twain.DIBToBMFile(handle, new_file) except twain.excDSTransferCancelled: print "There is/are no paper/papers in the feeder!" except twain.excTWCC_SEQERROR: Scanner.close_source() print "All the documents have been successfully scanned" except twain.excTWCC_BUMMER: print "Paper Jammed!"
def capture(ss): global index result = False try: rv = ss.XferImageNatively() fileName = str(index) + '_image.bmp' index += 1 #print rv; if rv: (handle, count) = rv # simpan gambar kedalam file str_image = twain.DIBToBMFile(handle) # tampilkan object file di command prompt print Image.open(StringIO(str_image)) result = True except Exception as e: print str(e.message) return result
def SetImageFile(self, handle, Control): self.Control = Control try: self.Control.Log("twain.DIBToBMFile(0x%lx, '%s')" % (handle, TmpFileName)) twain.DIBToBMFile(handle, TmpFileName) except: self.Control.DisplayException("twain.DIBToBMFile()") return try: FileSize = int(os.stat(TmpFileName)[6] / 1000) self.SetTitle("View Image : %s [File Size = %dk]" % (TmpFileName, FileSize)) bmp = wx.Image(TmpFileName, wx.BITMAP_TYPE_BMP).ConvertToBitmap() self.bmpImage.SetBitmap(bmp) self.scrolledWindow1.maxWidth = bmp.GetWidth() self.scrolledWindow1.maxHeight = bmp.GetHeight() self.scrolledWindow1.SetScrollbars(20, 20, bmp.GetWidth()/20, bmp.GetHeight()/20) self.bmpImage.Refresh() except: self.Control.DisplayException("View Bitmap")
def scan(self, output_name): """ scan and return PIL object if sucess else return False. The input is the complete name of the file to scan (directory + filename). For the moment only tesed JPEF format. TODO: test other formats """ print("enter in the scan method..") self.scanner.RequestAcquire(0, 1) info = self.scanner.GetImageInfo() self.handle = self.scanner.XferImageNatively()[0] img = twain.DIBToBMFile(self.handle, output_name) twain.GlobalHandleFree(self.handle) img_scanned = Image.open(output_name) img_scanned.save(output_name, self.config.scan_format, dpi=(self.config.dpi, self.config.dpi)) return img_scanned
async def scan(self, callback, device=None, dpi=None): if not self.sourceManager: self.start() devices = self.getScanners() if device: self.setScanner(device) else: self.setScanner(devices[0]) print(self.scanner) if dpi: self.setDPI(dpi) self.setPixelType("color") self.setScanArea() self.scanner.RequestAcquire(0, 1) info = self.scanner.GetImageInfo() try: self.handle = self.scanner.XferImageNatively()[0] image = twain.DIBToBMFile(self.handle) twain.GlobalHandleFree(self.handle) self.close() #check the folder exists if not os.path.exists("temp"): os.mkdir("temp", 0o777) img = Image.open(BytesIO(image)) filename = str(time.time()) + '.jpg' img.save('temp/' + filename) await callback(filename) return True except Exception as e: print(e) return False
import twain sm = twain.SourceManager(0) ss = sm.OpenSource() ss.RequestAcquire(0, 0) rv = ss.XferImageNatively() if rv: (handle, count) = rv twain.DIBToBMFile(handle, 'image.bmp')
def processTransfer(self, event): directory = "\\\\files.dcarf\\teleactive\\PDFs\\To be processed\\" #directory = "H:\\Desktop\\" #temp_directory = "\\\\files.dcarf\\tmp\\MailTracking\\" #from time import strftime,localtime #filename = strftime("%Y-%m-%d-%H-%M-%S",localtime()) + ".pdf" #if os.access(directory, os.W_OK): # c = canvas.Canvas(directory + filename) #elif os.access(temp_directory, os.W_OK): # print "Unable to write to teleactive directory. Writing output " + \ # "to " + temp_directory # c = canvas.Canvas(temp_directory + filename) #else: # print "Unable to write output file. Terminating scan" # return #c.setPageCompression(1) remaining = 1 if self.control.GetValue() == "": from time import strftime, localtime self.control.SetValue(strftime("%Y-%m-%d-%H-%M-%S", localtime())) val = self.control3.GetValue() + self.control.GetValue() count = 0 c = 0 filename = "" #print self.calendar.GetDate() while remaining > 0: #print "Remaining gt 0 : %s" % remaining val = self.control3.GetValue() + self.control.GetValue() count = 0 c = 0 self.numPages = int(self.control2.GetValue()) while self.numPages > 0: count = count + 1 #print "COUNT: %s PAGES: %s REMAINING: %s" % (count,self.numPages,remaining) #fn = temp_directory + "tmp" + str(count) + ".gif" #tmp_string = StringIO.StringIO() (handle, remaining) = self.scanner.XferImageNatively() #print "handle %s" % handle #print "remaining %s" % remaining #twain.DIBToBMFile(handle, fn) #Image.open(StringIO.StringIO(twain.DIBToBMFile(handle))).save( \ # fn, "GIF") temp_img = Image.open( StringIO.StringIO(twain.DIBToBMFile(handle))) (width, height) = temp_img.size if self.radio1.GetSelection() == 0: #A3 - so split page a4a = temp_img.crop((0, 0, int(width) / 2, height)) a4a.load() a4b = temp_img.crop((int(width) / 2, 0, width, height)) a4b.load() img = temp_img.resize((int(width) / 2, int(height) / 2), \ Image.ANTIALIAS) (width, height) = a4a.size imga = a4a.resize((int(width) / 2, int(height) / 2), \ Image.ANTIALIAS) (width, height) = a4b.size imgb = a4b.resize((int(width) / 2, int(height) / 2), \ Image.ANTIALIAS) else: # A4 don't split img = temp_img.resize((int(width) / 2, int(height) / 2), \ Image.ANTIALIAS) twain.GlobalHandleFree(handle) if c == 0: filename = val + ".pdf" if os.access(directory, os.W_OK): c = canvas.Canvas(directory + filename) c.setPageCompression(1) if self.radio1.GetSelection() == 0: #A3 - so split page c.drawInlineImage(imga, 0, 0, 600, 849) c.showPage() c.drawInlineImage(imgb, 0, 0, 600, 849) c.showPage() else: # A4 don't split c.drawInlineImage(img, 0, 0, 600, 849) c.showPage() self.numPages = self.numPages - 1 c.save() print "SAVED to %s.pdf" % val if self.radio3.GetSelection() != 0: upload(directory + filename, self.control.GetValue()).start() self.control.SetValue("")
# sumber data dari scanner sm = twain.SourceManager(0) ss = sm.OpenSource() ss.RequestAcquire(0, 0) # set capability try: ss.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32, 200.0) ss.SetCapability(twain.ICAP_XRESOLUTION, twain.TWTY_FIX32, 200.0) except Exception as e: print str(e.message) rv = ss.XferImageNatively() if rv: (handle, count) = rv str_image = twain.DIBToBMFile(handle) twain.GlobalHandleFree(handle) # tampilkan object file di command prompt print Image.open(StringIO(str_image)) elif (feeder == True): index = 0 def next(ss): try: # cetak image info # tidak ditampilkan hanya sebagai checking image saja ss.GetImageInfo() return True except: return False
sm = twain.SourceManager(0) print 'Scanning column ' + str(n + 1) + '/' + str(nCols) + '...' # Open the source using the string with the name of the scanner. # If you want to see available scanner names, just call this: # sm.GetSourceList() # ...and you will get a list of all scanners connected to the computer. # # For testing: # sd = sm.OpenSource('TWAIN2 FreeImage Software Scanner 2.1') sd = sm.OpenSource('WIA-HP Scanjet G4050') #set resolution to 600dpi x_res = sd.SetCapability(twain.ICAP_XRESOLUTION, twain.TWTY_FIX32, float(600)) y_res = sd.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32, float(600)) sd.RequestAcquire(0, 0) (handle, count) = sd.XferImageNatively() twain.DIBToBMFile(handle, 'image' + str(n + 1) + '.jpg') # Deleting these and recreating sm and sd each iteration avoids excTWCC_SEQERROR del sm del sd if (n < nCols - 1): ser.write(INIT) else: print 'Finished!'