Python Sample: Acquire and save to BMP file

Top  Previous  Next

The following Python script is all that is required to do the following:

 

Check if TWAIN is installed.

Initialize the DTWAIN Dynamic Link Library.

Select a Source

Acquire a page using the Native transfer mode

Save page to a BMP file called "test.bmp"

Shut down any open TWAIN Source's and DTWAIN itself

 


from ctypes import *

import dtwain

import ctypes as ct


def test_dtwain():

    # Load the DTWAIN library (make sure "dtwain32u.dll" is accessible)

    # You can use a full pathname here also, to ensure python finds the dll

    dtwain_dll = windll.LoadLibrary("dtwain32u.dll") 

    

    # Initialize DTWAIN

    dtwain_dll.DTWAIN_SysInitialize()

    

    # Select a TWAIN source

    TwainSource = dtwain_dll.DTWAIN_SelectSource()

    if TwainSource:

        # Display the product name of the Source

        mystrbuf = ct.create_string_buffer(100)

        dtwain_dll.DTWAIN_GetSourceProductNameA(TwainSource,mystrbuf,len(mystrbuf))

        print (mystrbuf.value)

        

        # Acquire to a BMP file

        dtwain_dll.DTWAIN_AcquireFile(TwainSource, "TEST.BMP", dtwain.DTWAIN_BMP, dtwain.DTWAIN_USELONGNAME,

                                      dtwain.DTWAIN_PT_DEFAULT, 1, 1, 1, 0)

    # Close down DTWAIN                                      

    dtwain_dll.DTWAIN_SysDestroy()


if __name__ == '__main__':

    test_dtwain()


Note that the cTypes facility of Python is used to load the DTWAIN32.DLL and call the DTWAIN functions.  Since the DTWAIN functions all use the stdcall calling convention, the windll.LoadLibrary must be used to correctly load DTWAIN32.DLL (do not use the cdll version of LoadLibrary!).

 

Also, the import dtwain imports the constants defined by the DTWAIN library.  For the import to succeed, the dtwain.py module contains the constant definitions, and should be located in your Python's path for imports (or in the same directory as your Python scripts).