2016-01-21 266 views
0

我正在Python中開發一個應用程序。我已經丟失了文件給掃描儀。所以當按下按鈕時,我想掃描所有這些文件並保存到程序中。如何在Twain中掃描多個文件

import twain 

sm = twain.SourceManager(0) 
ss = sm.OpenSource() 

for i in range(3): //for ex. 3 documents in the scanner device 
    ss.RequestAcquire(0,0) 
    rv = ss.XferImageNatively() 
    if rv: 
     (handle, count) = rv 
     twain.DIBToBMFile(handle, '{i}.bmp'.format(i)) 

當按下按鈕掃描所有文件但不能保存到程序中時。我有一個錯誤twain.excTWCC_SEQERROR。那我該如何解決這個問題?

回答

2

發送請求後,您必須等待圖像準備就緒。因此,你需要根據TWAIN module document設置事件的回調:

SourceManager.SetCallback(pfnCallback) 
This method is used to set the callback handler. The callback handler is invoked when the TWAIN source signals our application. It can signal our application to indicate that there is data ready for us or that it wants to shutdown. 
The expected events are: 
MSG_XFERREADY (0x101) - the data source has data ready 
MSG_CLOSEDSREQ (0x0102) - Request for Application. to close DS 
MSG_CLOSEDSOK (0x0103) - Tell the Application. to save the state. 
MSG_DEVICEEVENT (0X0104) - Event specific to Source 

一個可能的代碼更改:

import twain 

sm = twain.SourceManager(0) 
sm.SetCallback(onTwainEvent) 
ss = sm.OpenSource() 
index = 0 

for i in range(3): //for ex. 3 documents in the scanner device 
    ss.RequestAcquire(0,0) 

def onTwainEvent(event): 
    if event == twain.MSG_XFERREADY: 
     saveImage() 

def saveImage(): 
    rv = ss.XferImageNatively() 
    if rv: 
     (handle, count) = rv 
     twain.DIBToBMFile(handle, '{index}.bmp'.format(index)) 
     index += 1 

您也可以參考pytwain code

+0

如何將DIBToBMFile更改爲JPEG? – YumYumYum

+0

在我的情況下,「onTwainEvent」永遠不會被解僱。 – YumYumYum