Introduction to TDelphiTwain

Welcome to my contribution to Delphi community, TTwain

component. This component enables any Delphi application to use most of the latest Twain features from the specification.

Items with the [image] icon means that it is for advanced implementations

What do you want to do ?

  1. Read more about Twain and it's pruposes
    Read about how Twain was created, who and what supports it and why to use it

  2. Learn how to acquire an image from a twain device
    Tutorial about on how to obtain the image from any acquire device (scanners, webcams...)

  3. Most common capabilities used by devices
    This is briefly explain the most common properties which are used by most of the devices

  4. Retrieving and setting any property or capability
    Tutorial explaining how to set and retrieve capabilities from twain not handled by the component
TWAIN license information and acknowledgements.
For questions or comments about TWAIN, contact the TWAIN Working Group


TDelphiTwain component

Components > TDelphiTwain

The TDelphiTwain is the main component. It is also responsible for handling the Source Manager implementation. The component is also registered in Delphi component palette after you install the package:

This is the main component icon located at Delphi component palette after you install it

1 First step, setting application info
The component needs to inform Twain with some info about the current application. To do so, use Info property to fill the information.

2 Second step, loading the library
Also the component dynamically loads Twain library using the LibraryLoaded property and setting it to TRUE. In case the property continues to FALSE even after you set to TRUE it means that Twain library is not loaded. Also you may use the LoadLibrary() which sets the property to TRUE and returns if it loaded successfully.

3 Third step, load source manager
After the library was loaded, you should now load the source manager, which is the main twain module to control the sources. Loading the source manager may be done by setting SourceManagerLoaded to TRUE or calling LoadSourceManager().

4 Last step, using the events
Also, the component provides different events to allow the application to receive notifications either to receive the acquired image (OnTwainAcquire / OnSourceFileTransfer), unexpected events (OnAcquireCancel / OnAcquireError), progress for memory transfer (OnAcquireProgress) and setup for file transference (OnSourceSetupFileXfer).

Transference modes
This component implements the three transference modes from Twain latest specification: Native Handle; File; Memory. This may be set by using either TDelphiTwain TransferMode property or for each source TransferMode property. The three transference modes are better explained here.

What is next ?
Now that booth library and source manager are loaded, the sources are available to the application. Source is implemented through TTwainSource objects. To get it use Source[index: Integer], and to get the number of sources use SourceCount property.

Allowing the final user to choose a source
There are two different ways to allow the user to select one of the available sources:

  1. By calling SelectSource() method which displays a dialog to allow the user to select a source and returns the selected source index or -1 if user canceled (or none was available).
  2. Using Source[index: Integer] property which returns each source info, allowing the application to use a list control to allow the user to choose a source.
TWAIN license information and acknowledgment.


property AppIdentity

TDelphiTwain > Properties > AppIdentity

Returns a pointer to the application TW_IDENTITY.

property AppIdentity: pTW_IDENTITY;

Description
This property returns a pointer to the pTW_IDENTITY structure which is responsable for holding application information to pass to Twain. The TW_IDENTITY that this property points to is holded by the TTwainIdentity object returned by the property Info. When you change the property Info, this structure is automatically updated.

Comments
This property is only useful when you're making direct calls to Twain using TwainProc property.


property HasEnumerated

TDelphiTwain > Properties > HasEnumerated

Returns if the source list has being enumerated yet.

property HasEnumerated: Boolean;

Description
This property returns if the source list has being enumerated yet. The source list is automatically enumerated after you read the properties SourceCount and Source[Index: Integer]. The list may also be re-enumerated using the method EnumerateDevices.


property Handle

TDelphiTwain > Properties > Handle

Returns the handle for twain library DLL.

property Handle: hInst;

Description
This property returns a handle for TWAIN_32.DLL library. This value is only avaliable after LibraryLoaded is set to TRUE (or when LoadLibrary() method is called). This handle might not be too useful because there is only one method in Twain library, DSM_Entry, which may be used calling the method TwainProc.


property Info

TDelphiTwain > Properties > Info

Defines application information to Twain

property Info: TTwainIdentity;

Description
Applications should fill all the sub-properties from this property to tell twain source/source manager about the current application. To learn about this property check TTwainIdentity description.


property LibraryLoaded

TDelphiTwain > Properties > LibraryLoaded

Controls if the twain library TWAIN_32.DLL is dynamically loaded.

property LibraryLoaded: Boolean;

Description
This property is used booth in design and in run time to load or unload the main twain library from the memory. This property must be TRUE before most of the other properties be used.

Comments
If you set this property to TRUE and it's value continues to be FALSE, it means that either the Twain is not installed (check twain library info) or there was not enough memory.


property SourceCount

TDelphiTwain > Properties > SourceCount

Returns the number of sources avaliable for Twain.

property SourceCount: Integer;

Description
This read-only property returns the number of sources avaliable to the application. The sources may be accessed using the property Source[Index:Integer] using index from 0 to SourceCount - 1. This value is only correctly avaliable after SourceManagerLoaded is TRUE.


property SourceManagerLoaded

TDelphiTwain > Properties > SourceManagerLoaded

Controls if the Twain source manager is loaded or not.

property SourceManagerLoaded: Boolean;

Description
The property loads/unloads Twain source manager allowing to have access to the sources and methods provided by Twain. Most of the methods needs this property to be set before they can be used.


property Source[Index: Integer]

TDelphiTwain > Properties > Source[Index: Integer]

Returns an object for any installed source.

property Source[Index: Integer]: Integer;

Description
This property is used to return TTwainSource objects for all the sources available for Twain. The source list is internally enumerated after the first time you call Source property (or SourceCount). Possible values for Index starts with 0, which is the first item to SourceCount - 1, which is the last. Also, there is a special index which is -1 that returns the default source.

Use the TTwainSource returned by this property to retrieve information on the source and also to do the process of acquiring images.


property TransferMode

TDelphiTwain > Properties > TransferMode

Specifies the default transfer mode for the sources.

type TTwainTransferMode = (ttmFile, ttmMemory, ttmNative);

property TransferMode: TTwainTransferMode;

Description
This property specifies the default transfer mode for the sources. The value may be override by each source by setting source TransferMode property.


property TwainProc

TDelphiTwain > Properties > TwainProc

Returns handle to method to directly access twain features.

type TDSMEntryProc = function(pOrigin: pTW_IDENTITY;
pDest: pTW_IDENTITY; DG: TW_UINT32; DAT: TW_UINT16;
MSG: TW_UINT16; pData: TW_MEMREF): TW_UINT16; stdcall;

property TwainProc: TDSMEntryProc;

Description
The property returns a pointer to Twain main and only method, DSM_Entry. This method is internally responsible for the communication between the application and the source manager. This method doesn't need to be used since the component internally already handles it.

Comments
To successfully use this method is recommended to include Twain unit in the uses clause to support all the types provided by Twain. Also read about twain types, and the tutorial on how to directly call Twain.


method EnumerateDevices

TDelphiTwain > Method > EnumerateDevices

Enumerate the current twain sources.

function EnumerateDevices(): Boolean;

Description
There is not necessity to call EnumerateDevices() since it is called automatically when the source list is needed. EnumerateDevices() method serves to re-enumerate the source list after it has being enumerated.
To check if the list has being already created, use HasEnumerated.

Return values
Returns TRUE if the method was successful.


method LoadLibrary

TDelphiTwain > Method > LoadLibrary

Loads twain library and set LibraryLoaded to TRUE.

function LoadLibrary(): Boolean;

Description
This method loads Twain library. If the library was successfully loaded, LibraryLoaded is set to TRUE.

Return values
Returns TRUE if the library was successfully loaded. If it returns FALSE, it means that Twain is not installed in the current machine.


method LoadSourceManager

TDelphiTwain > Method > LoadSourceManager

Loads twain source manager and sets SourceManagerLoaded to TRUE.

function LoadSourceManager(): Boolean;

Description
This method loads the source manager which is responsible for controlling twain features and sources. If this method was successful, SourceManagerLoaded is set to TRUE.

Return values
Returns TRUE if the source manager was successfully loaded.


method SelectSource

TDelphiTwain > Method > SelectSource

Shows a Twain dialog to allow the user to select a source.

function SelectSource(): Integer;

Description
This method display a common twain dialog that displays the list of all sources avaliable for the application. For an example on using this method, check the first tutorial.

Return values
Returns the index of the selected item or -1 if user cancelled or if there was no sources to select.


method UnloadLibrary

TDelphiTwain > Method > UnloadLibrary

Unloads twain library and set LibraryLoaded to FALSE.

function UnloadLibrary(): Boolean;

Description
This method unloads Twain library. All the sources and the source manager are also unloaded.

Return values
Returns TRUE if the library was successfully unloaded.


method UnloadSourceManager

TDelphiTwain > Method > LoadSourceManager

Unloads twain source manager and sets SourceManagerLoaded to FALSE.

function UnloadSourceManager(): Boolean;

Description
UnloadSourceManager unloads the source manager from memory. It also unloads any loaded source from memory.

Return values
Returns TRUE if the source manager was successfully unloaded.


Event OnAcquireCancel

TDelphiTwain > Events > OnAcquireCancel

This event is called
        when the user cancels an image acquire.

type TSourceNotify = procedure(Sender: TObject;
const Index: Integer) of object;

property OnAcquireCancel: TSourceNotify;

Description
The event is called just after the user manually cancels an image acquire. Index parameter is the position in Source[Index: Integer].


Event OnAcquireError

TDelphiTwain > Events > OnAcquireError

Called when something
        went wrong when acquiring an image.

type TOnTwainError = procedure(Sender: TObject;
const Index: Integer; ErrorCode, Additional: Integer)
        of object;

property OnAcquireError: TOnTwainError;

Description
This event is called for all transference modes when something went wrong while acquiring. ErrorCode contains the code returned by Twain and Additional, the additional information for the error. It's necessary to include twain in the uses clause to use error constants. The error constants for ErrorCode and Additional parameters are in this page.


Event OnAcquireProgress

TDelphiTwain > Events > OnAcquireProgress

Progress notification
        when transference mode is ttmMemory.

type TOnAcquireProgress = procedure(Sender: TObject;
const Index: Integer; const Image: HBitmap;
const Current, Total: Integer) of object;

property OnAcquireProgress: TOnAcquireProgress;

Description
This event is only used when TransferMode property is set to ttmMemory. It's called for each line transferred from the source to the application. Current is the actual line transferred and Total the number of lines in the image. Image contains a windows handle for the image being transferred.

To use Image parameter you have several options, including:

  • Creating a new bitmap object (TBitmap) and setting it handle property to Image (the parameter). The object will be ready to be used.
  • Calling one of windows API methods. Recommends using DrawState method (see Windows API reference)

This event is useful for low speed image acquire such as scanners to display the image as it is being acquired (the scanner must support this).

It HBitmap instead of a TBitmap object for speed purposes.


Event OnSourceDisable

TDelphiTwain > Events > OnSourceDisable

Called after a source
        has being disabled.

type TSourceNotify = procedure(Sender: TObject;
const Index: Integer) of object;

property OnSourceDisable: TSourceNotify;

Description
This event is called after the source has being disabled. This happens after the source has finished acquiring an image. Also it is called after you set Enabled property to FALSE or call DisableSource.

The index parameter in the event holds the position of the source in the Source[Index: Integer] property which this event is for.


Event OnSourceFileTransfer

TDelphiTwain > Events > OnSourceFileTransfer

Called when the transference
        mode is ttmFile and
        the image was successfully transferred.

type
        TTwainFormat = (tfTIFF, tfPict, tfBMP, tfXBM, tfJPEG, tfFPX,
tfTIFFMulti, tfPNG, tfSPIFF, tfEXIF, tfUnknown);

type TOnSourceFileTransfer = procedure(Sender: TObject;
const Index: Integer; Filename: TW_STR255; Format:
        TTwainFormat;
var Cancel: Boolean) of object;

property OnSourceFileTransfer: TOnSourceFileTransfer;

Description
This method is called after an image is transferred when TransferMode property is set to ttmFile. If the source supports multiple images, this event will be called for each image. Use the property PendingXfers to get the number of remaining images. To cancel the next images, set the parameter Cancel to TRUE.

After this event is called, the application should use the Filename parameter (string[255]) to load the file. The file format is specified in the Format parameter.


Event OnSourceSetupFileXfer

TDelphiTwain > Events > OnSourceSetupFileXfer

This event is called in order to allow the user to prepare for the transference of images when transference mode is ttmFile.

type TSourceNotify = procedure(Sender: TObject;
const Index: Integer) of object;

property OnSourceSetupFileXfer: TSourceNotify;

Description
This event is called before an image is transferred to the application when TransferMode property is set to ttmFile. File transference mode allows that the user select the place that the file should be saved into and the format it should have.

The file location and format is be set using method SetupFileTransfer from a TTwainSource object. In case this method returns FALSE, it means that either the file location is invalid or the format is not supported.

Index is the position of the source in the property Source[Index: Integer]. The file is then transferred using the event OnSourceFileTransfer.

Also, if the source intend to transfer multiple images, this event will be called for each image to allow the user to configure each. To get the number of pending images, use PendingXfers.


Event OnTwainAcquire

TDelphiTwain > Events > OnTwainAcquire

Event called after an image was acquired using Transfer mode ttmNative or ttmMemory.

type TOnTwainAcquire = procedure(Sender: TObject;
const Index: Integer; Image: TBitmap; var Cancel: Boolean) of object;

property OnTwainAcquire: TOnTwainAcquire;

Description
TOnTwainAcquire is called after the image was successfully transferred from the Source to the Application. In case of the source provide multiple images, this event will be called multiple times. The transference of the next images may be canceled by setting Cancel parameter to TRUE.

The Image parameter contains the acquired image. You may copy this image using Assign method, but never destroy TBitmap the object.

To get the number of pending images to transfer, use the TTwainSource PendingXfers property. It might return -1 in case the number of pending images is not definied.

Also, index parameter contains the index of source which is sending the acquired image.

Comments
This event is called only if the TransferMode is as ttmNative or ttmMemory. For ttmFile mode, OnSourceFileTransfer is called.


TTwainIdentity

This object is responsible for handling the Twain TW_IDENTITY structure (which needs not to be understanded). It provides properties which contain information about some container.

It is implemented for TDelphiTwain Info property and it is also the class which TTwainSource descends from. The difference is that TTwainSource re-implement the properties to be read-only because they should not be modified since each source provides it.


property CountryCode

TTwainIdentity > Properties > CountryCode
(for Info property) [image] (For sources)

Country code for the application.

property CountryCode: Word;

Description
You should fill this property with the country code for the current application. Check the country codes page to know the country code for any country.


property Groups

TTwainIdentity > Properties > Groups
(for Info property) [image] (For sources)

Set of features used by the application or source.

type TTwainGroups = set of (tgControl, tgImage, tgAudio);

property Groups: TTwainGroups;

Description
When set by the application (using Info property), this defines the groups of features that the application may requested. When defined by the source, it is the groups of features that the source supports:

tgControl | This value should always be set. It allows the application to have access to the sources and to the source manager features.
tgImage | Set this when the application needs to acquire images from the sources. This value is usually set and should remain as it is.
tgAudio | Allows the application to have audio acquire from the sources. This is not commonly used, but might be useful.


property Language

TTwainIdentity > Properties > Language
(for Info property) [image] (For sources)

Application language.

type TTwainLanguage = (tlUserLocale, tlDanish, tlDutch,
tlInternationalEnglish, tlFrenchCanadian, tlFinnish, tlFrench, tlGerman,
tlIcelandic, tlItalian, tlNorwegian, tlPortuguese, tlSpanish, tlSwedish,
tlUsEnglish, tlAfrikaans, tlAlbania, tlArabic, tlArabicAlgeria,tlArabicBahrain, tlArabicEgypt, tlArabicIraq, tlArabJordan, tlArabicKuwait, tlArabicLebanon,
tlArabicLibya, tlArabicMorocco, tlArabicOman, tlArabicQatar,
tlArabicSaudiarabia, tlArabicSyria, tlArabicTunisia, tlArabicUae,
tlArabicYemen, tlBasque, tlByelorussian, tlBulgarian, tlCatalan, tlChinese,
tlChineseHongkong, tlChinesePeoplesRepublic, tlChineseSingapore,
tlChineseSimplified,tlChineseTwain, tlChineseTraditional, tlCroatia, tlCzech, tlDutchBelgian, tlEnglishAustralian, tlEnglishCanadian, tlEnglishIreland,
tlEnglishNewZealand, tlEnglishSouthAfrica, tlEnglishUk, tlEstonian,
tlFaeroese, tlFarsi, tlFrenchBelgian, tlFrenchLuxembourg, tlFrenchSwiss,
tlGermanAustrian, tlGermanLuxembourg, tlGermanLiechtenstein,
tlGermanSwiss, tlGreek, tlHebrew, tlHungarian, tlIndonesian, tlItalianSwiss, tlJapanese, tlKorean, tlKoreanJohab, tlLatvian, tlLithuanian,
tlNorewgianBokmal, tlNorwegianNynorsk, tlPolish, tlPortugueseBrazil,
tlRomanian, tlRussian, tlSerbianLatin, tlSlovak, tlSlovenian,
tlSpanishMexican, tlSpanishModern, tlThai, tlTurkish, tlUkranian,
tlAssamese, tlBengali, tlBihari, tlBodo, tlDogri, tlGujarati, tlHarayanvi,
tlHindi, tlKannada, tlKashmiri, tlMalayalam, tlMarathi, tlMarwari,
tlMeghalayan, tlMizo, tlNaga, tlOrissi, tlPunjabi, tlPushtu, tlSerbianCyrillic,
tlSikkimi, tlSwidishFinland, tlTamil, tlTelugu, tlTripuri, tlUrdu, tlVietnamese);

property Language: TTwainLanguage;

Description
This property defines the current application language. You should select one item from the TTwainLanguage enumeration or leave tlUserLocale to select the current Windows language as the application language.


property MajorVersion

TTwainIdentity > Properties > MajorVersion
(for Info property) [image] (For sources)

Major version for the application

property MajorVersion: Integer;

Description
Defines the application major version, for instance, if the application version is 1.53, the major version is the 1 part


property Manufacturer

TTwainIdentity > Properties > Manufacturer
(for Info property) [image] (For sources)

Application manufacturer.

property Manufacturer: String;

Description
Should hold the author of the application. For instance “Gustavo Daud”.

Comments
The maximum allowed size is 31 characters.


property MinorVersion

TTwainIdentity > Properties > MinorVersion
(for Info property) [image] (For sources)

Minor version for the application

property MinorVersion: Integer;

Description
Defines the application minor part of the version, for instance, if version is 1.53, the minor version part is “53”.


property ProductFamily

TTwainIdentity > Properties > ProductFamily
(for Info property) [image] (For sources)

Product family for the application.

property ProductFamily: String;

Description
Product family for the application. For instance “Microsoft Office” in case the product name is “Word for Windows”.

Comments
The maximum allowed size is 31 characters.


property ProductName

TTwainIdentity > Properties > ProductName
(for Info property) [image] (For sources)

Name of the application.

property ProductName: String;

Description
Should contain the name of the application.

Comments
The maximum allowed size is 31 characters.


property VersionInfo

TTwainIdentity > Properties > VersionInfo
(for Info property) [image] (For sources)

Some name for the current application with version.

property VersionInfo: String;

Description
You should define here the name for the application with a version identifier in the end. For instance “My application 2002”.

Comments
The maximum allowed size is 31 characters.


method Assign

TTwainIdentity > Methods > Assign

Copies all the properties from another TTwainIdentity object.

procedure Assign(Source: TPersistent);

Description
This method takes the other Source from the parameter (which should be another TTwainIdentity object) and copies all it's properties to the current object. This method is used internally and there is no need to use it.


TTwainSource component

Components > TTwainSource

This object is responsible for handling a Twain source. A list of source may be obtained using SourceCount and Source[Index: Integer] properties from a TDelphiTwain object.

It is using the source object that you may acquire images. More than one source may be loaded and enabled at the same time.

Main actions
Loading a source with Loaded property
Before using a source you must set Loaded property to TRUE (or call LoadSource() method). This makes internally the source manager loads the source library from memory and initialize it. Unloading the TDelphiTwain library or source manager (LibraryLoaded or SourceManagerLoaded to FALSE) automatically unloads all the loaded source from memory.

Enabling a source
Enable a source allows it to displays it interface to acquire the image. Also if user interface is transferred it makes the source automatically transfer the acquired image. Enabling a source may be done by setting Enabled property to TRUE.

Secondary actions
User interface
A source may or may not display it's user interface, which is the dialog it display to allow the user to select the options to acquire the image. This can be controllable using ShowUI property and setting it to TRUE or FALSE.

Some sources though may display it even if ShowUI is set to FALSE. To test if the source interface can be disable, try using the method GetUIControllable.

Transference Mode
All the sources support at least two different transference modes, Memory and Native Handle. A third, file transference is usually supported too. To change the transference mode use TransferMode property or call the method ChangeTransferMode to change the transference mode and return if it was able to change. Read more about transference modes here.

Capabilities
Twain support different capabilities for the sources, which are properties that you may set for it. There are two ways to set them: using predefined methods for the most common methods (check the properties for TTwainSource in the help) and by calling methods to set other twain properties using this tutorial.

Events
After an image has being transferred, some error or the component needs to inform status, some events are called. The events are implemented in the TDelphiTwain component and all events which relate to a source have an Index property that points to the source in question.

Source information
The source also provides information about itself as ProductName, ProductFamily, VersionInfo, etc. This allows the application to gather information about each source.


property Enabled

TTwainSource> Properties > Enabled

Enables the source to transfer acquired images.

property Enabled: Boolean;

Description
Set this property to TRUE to start the process of transferring the image from the source to the application. If ShowUI is set to FALSE, no user interface should be displayed and the image will be transferred automatically.

If Modal property is set to TRUE, the current application form will become disabled until source window is closed.

The image will be transferred to the application using the method selected in the property TransferMode using the TDelphiTwain component events.
Read more about different transfer modes here.

In case user cancels the source dialogs, the event OnAcquireCancel will be called to notify the application.

After the user interface is closed or the image is transfered, the property will be re-set to FALSE and the event OnSourceDisable will be called.


property Index

TTwainSource> Properties > Index

Returns the position of this source object in the source list.

property Index: Integer;

Description
This read-only property contains the position of the current TTwainSource object in the source list. The source list may be obtained using the methods from TDelphiTwain SourceCount and Source[Index: Integer].


property Loaded

TTwainSource> Properties > Loaded

Loads/Unloads the current source.

property Loaded: Boolean;

Description
This property loads or unloads the current TTwainSource object. Loading the source is necessary before calling any method from the source (except from the ones inherited from TTwainIdentity). You might also call LoadSource() method to load the source. If you set Loaded to TRUE and it continues FALSE, it means that the source could not be loaded.


property Modal

TTwainSource> Properties > Modal

Sets if the windows showed by the source are modal.

property Modal: Boolean;

Description
This property sets if the windows displayed by the source are modal with the application windows. Setting this property to TRUE makes application windows disabled while source is displaying any window. This property is recommended to set to TRUE.


property Owner

TTwainSource> Properties > Owner

Returns a pointer to the TDelphiTwain owner.

property Owner: TDelphiTwain;

Description
This returns a pointer to the TDelphiTwain object owner for the current TTwainSource object.


property PendingXfers

TTwainSource> Properties > PendingXfers

Returns the number of remaining images to transfer.

property PendingXfers: Integer;

Description
This property returns the number of remaining images for the source transfer to the application. A special return is -1 when there isn't a defined number of images to return. This value is only valid when the source is enabled (Enabled is TRUE). To cancel the pending images set the Cancel parameter when you receive the events OnSourceFileTransfer or OnTwainAcquire.


property ShowUI

TTwainSource> Properties > ShowUI

Returns/Sets if the source will display it's user interface.

property ShowUI: Boolean;

Description
Use this property to set if the source will display it's user interface. If the interface is not displayed, the source will automatically acquire and transfer the image without no user interaction after user enables the source (Enabled property or EnableSource()).

Comments
Some sources may still display user interface even when ShowUI is set to FALSE. To check if it is possible to disable user interface, use the method GetUIControllable.


property SourceIdentity

TTwainSource > Properties > SourceIdentity

Returns a pointer to the sourceTW_IDENTITY.

property SourceIdentity: pTW_IDENTITY;

Description
This property returns a pointer to the pTW_IDENTITY structure which is responsable for holding source information. The TW_IDENTITY that this property points to is holded by the TTwainIdentity object which the current TTwainSource is inherited from.

Comments
This property is only useful when you're making direct calls to Twain using TwainProc property for using for pDest parameter.


property TransferMode

TTwainSource> Properties > TransferMode

Transference mode to use to transfer images from source to the application.

type TTwainTransferMode = (ttmFile, ttmNative, ttmMemory);

property TransferMode: TTwainTransferMode;

Description
This property set the transference mode that the source uses to transfer all the acquired image from the device to the application. Currently three are defined:

  • File - The source creates a file contained the acquired image in a place designed by the app. The event OnSourceSetupFileXfer is called when the source needs to know the place and format for the file. You should call SetupFileTransfer method to set the filename and format (otherwise a default is used). When the source has written the file it calls the event OnSourceFileTransfer to tell where it was written.
  • Native - The source transfers the image to the application using a windows HBITMAP structure. The transference is all done by the component which is transparent to the final application. After the image was successfully acquired, the event OnTwainAcquire is called.
  • Memory - Transfer blocks of memory containing the final image parts. Again the transference is transparent to the application being all done by the component. This event also calls OnTwainAcquire when the image is acquired, but it also calls OnAcquireProgress to give progress notifications about the image being transferred.

More about the three different transference modes can be read here.

Comments
To test if a transfer mode is supported, use ChangeTransferMode and check if it returns trSuccess instead of using this property.


method ChangeTransferMode

TTwainSource> Methods > ChangeTransferMode

Change the source transfer mode and return if it was successful.

type TTwainTransferMode = (ttmFile, ttmNative, ttmMemory);

 function ChangeTransferMode(
NewMode: TTwainTransferMode): TCapabilityRet;

Description
This method to the same work as TransferMode but it has the advantage of returning if this method was supported. This method is only useful when using file transfer mode (ttmFile) because it is the only one optional for the source to implement.

Return values
This method returns one of the TCapabilityRet values.


method DisableSource

TTwainSource> Methods > DisableSource

Forces the source to be disabled.

function DisableSource(): Boolean;

Description
This method is not recommended to be used. It forces closing the source windows and may cause to cancel all the current transferences.

Return values
Returns TRUE or FALSE if it was successfully disabled or not.


method EnableSource

TTwainSource> Methods > EnableSource

Enables the source to transfer acquired images.

function EnableSource(ShowUI, Modal: Boolean): Boolean;

Description
This method do the same as Enabled property. It difference is that instead of reading ShowUI and Modal properties from the object, it uses the ones from the parameter.

The method starts the process of transferring the image from the source to the application. If ShowUI parameter is set to FALSE, no user interface should be displayed and the image will be transferred automatically.
If Modal parameter is set to TRUE, the current application form will become disabled until source window is closed.

The method also sets the Enabled property to TRUE to tell the application that the source is currently working.

The image will be transferred to the application using the method selected in the property TransferMode using the TDelphiTwain component events.
Read more about different transfer modes here.

In case user cancels the source dialogs, the event OnAcquireCancel will be called to notify the application.

After the user interface is closed or the image is transfered, the property will be re-set to FALSE and the event OnSourceDisable will be called.

Return values
Returns TRUE or FALSE if it was successfully enabled or not.


Method GetAutoFeed

TTwainSource > Methods > GetAutoFeed

Returns if the AutoFeed capability is TRUE or FALSE:

function GetAutoFeed(var Return: WordBool): TCapabilityRet;

Description
This method will set the return parameter to TRUE or FALSE depending if the AutoFeed capability is set to TRUE or FALSE. Read more about this capability at SetAutoFeed method explanation.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetArrayValue

TTwainSource > Methods > GetArrayValue

Returns a group of associated individual values.

  type TGetCapabilityList
        = array of string;

function GetArrayValue(Capability, var ItemType: TW_UINT16;
var List: TCapabilityList; MemHandle: HGLOBAL = 0):
        TCapabilityRet;

Description
When taken as a whole, describes a single “value” for a capability. The values need have no relationship to one another aside from being used to describe the same “value” of the capability. Such an array of values is
useful to describe the for instance, the capability CAP_SUPPORTEDCAPS list. The List parameter will contain a list of strings which should be converted to the item type specified in the parameter ItemType. To get the number of items in the list, use delphi Length method. The first item is 0 and the last Length(List) - 1.

Don't use MemHandle or leave it to 0 by default. You can also use the Handle value returned by GetCapabilityRec.

Comments
Since list contains string types you should call an appropriate delphi conversion method to convert to integer (strtoint), floating type (strtofloat). Check the twain type returned by the method using the ItemType parameter returned.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetCapabilityRec

TTwainSource > Methods > GetCapabilityRec

Returns a capability handle value.

 function GetCapabilityRec(const
        Capability: TW_UINT16;
var Handle: HGLOBAL; Mode: TRetrieveCap;
var Container: TW_UINT16): TCapabilityRet;

Description
GetCapabilityRec is a special method to retrieve a capability using a HGLOBAL handle. A pointer to the capability structure may be obtained by using returned value from windows GlobalLock(Handle). The structure to be used is definied by Container variable by testing from a TWON_??? value. Mode is the desired mode to use to retrieve.

Comments
This method is perfect to be used together with GetOneValue / GetArrayValue / GetEnumerationValue / GetRangeValue when you don't the kind of container that the container will return. Use the handle variable with these other methods.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetCapXferCount

TTwainSource > Methods > GetCapXferCount

Number of images that the source intend to transfer to the application.

function GetCapXferCount(var
        Return: SmallInt;
Mode: TRetrieveCap = rcGet): TCapabilityRet;

Description
The source will fill the Return parameter with the number of images it intend to send to the application. Common values are:

1 Source will transfer only one image this session
-1 Source is going to transfer undefinied multiple images

Mode parameter can be one of the following:

  • rcGet - Default value. Used to retrieve the current capability value.
  • rcGetCurrent - Same as rcGet
  • rcGetDefault - Return will contain default value for the capability.
  • rcReset - Return values to the default

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetEnumerationValue

TTwainSource > Methods > GetEnumerationValue

Returns a group of individual values describing a capability.

  type TGetCapabilityList
        = array of string;

function GetEnumerationValue(Capability, var ItemType: TW_UINT16;
var List: TCapabilityList; var Current, Default:
        Integer;
Mode: TRetrieveCap = rcGet; MemHandle: HGLOBAL = 0):TCapabilityRet;

Description
The values are ordered from lowest to highest values, but the step size between each value is probably not uniform. Such a list would be useful to describe the discreet resolutions of a capture device supporting, say, 75, 150, 300, 400, and 800 dots per inch. List parameter contains an array with the values from the enumeration. Getting list number of items may be done by calling delphi Length method. First item is 0 and last Length(List) - 1. Current and Default parameters contains the current selected value from the list and source default, they are index positions from the list, not the actual values.

Don't use MemHandle or leave it to 0 by default. You can also use the Handle value returned by GetCapabilityRec.

Comments
Since list contains string types you should call an appropriate delphi conversion method to convert to integer (strtoint), floating type (strtofloat). Check the twain type returned by the method using the ItemType parameter returned.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


Method GetFeederEnabled

TTwainSource > Methods > GetFeederEnabled

Returns if the FeederEnabled capability is TRUE or FALSE:

function GetFeederEnabled(var Return: WordBool): TCapabilityRet;

Description
This method will set the return parameter to TRUE or FALSE depending if the FeederEnabled capability is set to TRUE or FALSE. Read more about this capability at SetFeederEnabled method explanation.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


Method GetFeederLoaded

TTwainSource > Methods > GetFeederLoaded

Reflect whether there are documents loaded in the Source’s feeder.

function GetFeederLoaded(var Return: WordBool): TCapabilityRet;

Description
Used by application to inquire whether there are documents loaded in the Source’s feeder. SetFeederEnabled method must equal set to TRUE to use this capability. The Return parameter will be filled with TRUE or FALSE.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetIBitDepth

TTwainSource > Methods > GetIBitDepth

Returns the current and possible pixel bit depths for the current value of GetIPixelType.

type TTwainBitDepth
        = array of word;

function GetIBitDepth(var Return: Word; var Supported: TTwainBitDepth;
Mode: TRetrieveCap): TCapabilityRet;

Description
This capability method returns the bit depth for the current value returned by GetICapPixelType using the parameter Return. Also it fills the Supported parameter with an array containing the supported bit depths.

Mode parameter can be one of the following:

  • rcGet - Default value. Used to retrieve the current capability value.
  • rcGetCurrent - Same as rcGet
  • rcGetDefault - Return will contain default value for the capability.
  • rcReset - Return values to the default

Comments
To get the number of items in the Supported parameter, use delphi Length method. Note that the first item is 0 and the last is Length(Supported) - 1.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetICapUnits

TTwainSource > Methods > GetICapUnits

Unless a quantity is dimensionless or uses a specified unit of measure, GetICapUnits returns the unit of measure for all quantities.

type TTwainUnit
        = (tuInches, tuCentimeters, tuPicas, tuPoints, tuTwips,
tuPixels, tuUnknown);
type TTwainUnitSet = set of TTwainUnit;

function GetICapUnits(var Return: TTwainUnit; var Supported:
TTwainUnitSet; Mode: TRetrieveCap = rcGet): TCapabilityRet;

Description
This method will return the current select unit of measure for the other measures methods using the parameter Return. It will also fill Supported parameter with all the supported values by the Source. Use mode as:

  • rcGet - Default value. Used to retrieve the current capability value.
  • rcGetCurrent - Same as rcGet
  • rcGetDefault - Return will contain default value for the capability.
  • rcReset - Return values to the default.

Read more about twain measures here.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetIPhysicalHeight

TTwainSource > Methods > GetIPhysicalHeight

The maximum physical height (Y-axis) the Source can acquire (measured in units from GetICapUnits).

function GetIPhysicalHeight(var
        Return: Extended;
Mode: TRetrieveCap = rcGet): TCapabilityRet;

Description
Return parameter will contain the obtained value. Mode parameter should be one of the values:

  • rcGet - Default value. Used to retrieve the current capability value.
  • rcGetCurrent - Same as rcGet
  • rcGetDefault - Return will contain default value for the capability.
  • rcReset - Return values to the default.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetIPhysicalWidth

TTwainSource > Methods > GetIPhysicalWidth

The maximum physical width (X-axis) the Source can acquire (measured in units from GetICapUnits).

function GetIPhysicalWidth(var
        Return: Extended;
Mode: TRetrieveCap = rcGet): TCapabilityRet;

Description
Return parameter will contain the obtained value. Mode parameter should be one of the values:

  • rcGet - Default value. Used to retrieve the current capability value.
  • rcGetCurrent - Same as rcGet
  • rcGetDefault - Return will contain default value for the capability.
  • rcReset - Return values to the default.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetIPixelFlavor

TTwainSource > Methods > GetIPixelFlavor

Sense of the pixel whose numeric value is zero (minimum data value)..

type TTwainPixelFlavor = (tpfChocolate, tpfVanilla, tpfUnknown);
type TTwainPixelFlavorSet = set of TTwainPixelFlavor;

function GetIPixelFlavor(var Return: TTwainPixelFlavor; var Supported:
TTwainPixelFlavorSet; Mode: TRetrieveCap = rcGet): TCapabilityRet;

Description
For example, consider a black and white image:
If GetIPixelType returns tbdBw then If GetIPixelFlavor Return parameter is tpfChocolate then Black = 0
Else if GetIPixelFlavor is tpfVanilla then White = 0

Also, the Supported parameter should contain the supported modes by the source. Check this parameter to see if a pixel flavor is supported.

Mode parameter can be one of the following:

  • rcGet - Default value. Used to retrieve the current capability value.
  • rcGetCurrent - Same as rcGet
  • rcGetDefault - Return will contain default value for the capability.
  • rcReset - Return values to the default

Comments
Sources may prefer a different value depending on GetIPixelType. Use Mode parameter to rcGetDefault to get source's preferred value.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetIPixelType

TTwainSource > Methods > GetIPixelType

The type of pixel data that a Source is capable of acquiring (for example, black and white, gray, RGB, etc.)..

type TTwainPixelType = (tbdBw, tbdGray, tbdRgb, tbdPalette, tbdCmy,
tbdCmyk, tbdYuv, tbdYuvk, tbdCieXYZ, tbdUnknown);
type TTwainPixelTypeSet = set of TTwainPixelType;

function GetIPixelType((var Return: TTwainPixelType; var Supported:
TTwainPixelTypeSet; Mode: TRetrieveCap = rcGet): TCapabilityRet;

Description
This method will fill the Return parameter with the current pixel type used to acquire the next image. Also, Supported will be filled with a set containing the supported pixel types by the current source. Mode must be one of the values bellow:

  • rcGet - Default value. Used to retrieve the current capability value.
  • rcGetCurrent - Same as rcGet
  • rcGetDefault - Return will contain default value for the capability.
  • rcReset - Return values to the default.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetIYResolution

TTwainSource > Methods > GetIYResolution

All the Y-axis resolutions the Source can provide.

function GetIYResolution(var
        Return: Extended;
var Values: TTwainResolution;
Mode: TRetrieveCap = rcGet): TCapabilityRet;

Description
Measured in units of pixels per unit as defined by GetICapUnits. That is, when the units are tuUnits, both GetIYResolution and GetIXResolution shall report 1 pixel/pixel. Some data sources like to report the actual number of pixels that the device reports, but that response is more appropriate in GetIPhysicalHeight and GetIPhysicalWidth.

Values parameter will contain a list of all supported resolutions by the source. Return will contain the current selected (or default).

Mode parameter should be one of the values:

  • rcGet - Default value. Used to retrieve the current capability value.
  • rcGetCurrent - Same as rcGet
  • rcGetDefault - Return will contain default value for the capability.
  • rcReset - Return values to the default.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetIXResolution

TTwainSource > Methods > GetIXResolution

All the X-axis resolutions the Source can provide.

function GetIXResolution(var
        Return: Extended;
var Values: TTwainResolution;
Mode: TRetrieveCap = rcGet): TCapabilityRet;

Description
Measured in units of pixels per unit as defined by GetICapUnits. That is, when the units are tuUnits, both GetIXResolution and GetIYResolution shall report 1 pixel/pixel. Some data sources like to report the actual number of pixels that the device reports, but that response is more appropriate in GetIPhysicalHeight and GetIPhysicalWidth.

Values parameter will contain a list of all supported resolutions by the source. Return will contain the current selected (or default).

Mode parameter should be one of the values:

  • rcGet - Default value. Used to retrieve the current capability value.
  • rcGetCurrent - Same as rcGet
  • rcGetDefault - Return will contain default value for the capability.
  • rcReset - Return values to the default.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetOneValue

TTwainSource > Methods > GetOneValue

Return the value from any twain capability which only returns one value.

 type TRetrieveCap
        = (rcGet, rcGetCurrent, rcGetDefault, rcReset);

function GetOneValue(Capability: TW_UINT16; var ItemType: TW_UINT16;
var Value: String; Mode: TRetrieveCap = rcGet;
MemHandle: HGLOBAL = 0): TCapabilityRet;

Description
Use this method to return the value from any twain capability that returns TW_ONEVALUE types. After you call this method, and if it returns crSuccess, ItemType parameter will contain the TWTY_?? constant, Value parameter will contain the retrieved value. Mode defines the value type you want to retrieve (rcGetDefault retrieves the default value and rcReset returns to default value).

Don't use MemHandle or leave it to 0 by default. You can also use the Handle value returned by GetCapabilityRec.

Comments
Since the value returned is a string type you should call an appropriate delphi convertion method to convert to integer (strtoint), floating type (strtofloat). Check the twain type returned by the method using the ItemType parameter returned.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method GetRangeValue

TTwainSource > Methods > GetRangeValue

Return the value from any twain capability which returns range values.

type TRetrieveCap = (rcGet, rcGetCurrent, rcGetDefault, rcReset);

function GetRangeValue(Capability: TW_UINT16; var ItemType:
TW_UINT16; var Min, Max, Step, Default, Current: String;
Mode: TRetrieveCap = rcGet; MemHandle: HGLOBAL = 0):
TCapabilityRet;

Description
Use GetRangeValue to get twain TW_RANGE values. This kind of capability return allows stores a range of individual values describing a capability. The values are uniformly distributed between a minimum (min parameter) and a maximum (max parameter) value. The step (step parameter) size between each value is constant. Such a value is useful when describing such capabilities as the resolutions of a device which supports discreet, uniform steps between each value, such as 50 through 300 dots per inch in steps of 2 dots per inch (50, 52, 54, ..., 296, 298, 300). Mode allows to set the mode to retrieve the values, rcGetDefault meaning to retrieve the source default values for the capability and rcReset returns the values to the default.

Don't use MemHandle or leave it to 0 by default. You can also use the Handle value returned by GetCapabilityRec.

Comments
Since the value returned is a string type you should call an appropriate delphi convertion method to convert to integer (strtoint), floating type (strtofloat). Check the twain type returned by the method using the ItemType parameter returned.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


Method GetReturnStatus

TTwainSource > Methods > GetReturnStatus

TCapabilityRet is a translation from twain return to the component set from a call to set one of twain properties or capabilities. The values are:

function GetReturnStatus: TW_UINT16;

Description
This method returns advanced error information for a direct call to Twain. See more about direct calls to Twain using TwainProc in this tutorial. The constants for the error values are here. You should also include twain unit in the uses clauses.


method GetUIControllable

TTwainSource > Methods > GetUIControllable

If TRUE, indicates that this Source supports acquisition with the UI disabled; i.e., ShowUI field can be set to FALSE. If FALSE, indicates that this Source
can only support acquisition with the UI enabled..

function GetUIControllable(var Return: WordBool): TCapabilityRet;

Description
A return value of crUnsupported / crBadOperation indicates that the Source in use is not TWAIN 1.6-compliant. Therefore, the Source may ignore
ShowUI parameter when EnableSource() is issued. Return parameter will hold the returned value.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method LoadSouce

TTwainSource> Methods > LoadSource

Loads the source and set Loaded to TRUE.

function LoadSource(): Boolean;

Description
This method tells Twain to load the source in memory and it setting the Loaded property to TRUE.

Return values
If the function returns FALSE it means that, for some reason the library could not be loaded not being then ready to be used.


method SetArrayValue

TTwainSource > Methods > SetArrayValue

Set a capability which stores a group of associated individual values.

  type TSetCapabilityList
        = array of pointer;

function SetArrayValue(Capability, ItemType: TW_UINT16;
List: TSetCapabilityList): TCapabilityRet;

Description
SetArrayValue is used to set a capability using twain TW_ARRAY. The capability contain a list of unrelated individual values of type related to ItemType. List parameter should contain a list of pointers for variables of type related to twain type from ItemType parameter declared on the application.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


Method SetAutoFeed

TTwainSource > Methods > SetAutoFeed

If TRUE, the Source will automatically feed the next page from the document feeder after the number of frames negotiated for capture from each page are acquired. SetFeederEnabled must be called with TRUE to use this capability.:

function SetAutoFeed(Value: WordBool): TCapabilityRet;

Description
Set the value to TRUE to enable the Source’s automatic feed process, or FALSE to disable it. After the completion of each transfer, check PendingXfers property. Count to determine if the Source has more images to transfer. A -1 means there are more images to transfer but the exact number is not known. GetFeederLoaded indicates whether the Source’s feeder is loaded. (The automatic feed process continues whenever this capability is TRUE.).

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method SetCapXferCount

TTwainSource > Methods > SetCapXferCount

Number of images that the application intend to transfer from the source.

function SetCapXferCount(Value: SmallInt): TCapabilityRet;

Description
The Value parameter should contain the number of images the application intend to receive from the source. Common values are:

1 Application wishes to transfer only one image this session
-1 Application is willing to transfer multiple images

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method SetEnumerationValue

TTwainSource > Methods > SetEnumerationValue

Sets a group of individual values describing a capability.

  type TSetCapabilityList
        = array of pointer;

function SetEnumerationValue(Capability, ItemType: TW_UINT16;
CurrentIndex: TW_INT32; List: TSetCapabilityList): TCapabilityRet;

Description
SetCapabilityValue parameter method sets a list of related values ordered from the lowest to the highest, not needing to be uniform. List should contain an array of pointers, each item should be a pointer to a variable of twain type related to ItemType declared by the application. CurrentIndex parameter is the position on the list of the currently selected item.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


Method SetFeederEnabled

TTwainSource > Methods > SetFeederEnabled

If TRUE, Source must acquire data from the document feeder acquire area and other feeder capabilities can be used. If FALSE, Source must acquire data from the non-feeder acquire area and no other feeder capabilities can be used

function SetFeederEnabled(Value: WordBool): TCapabilityRet;

Description
The application should set this capability to TRUE before attempting to use any other feeder capabilities. This sets the current acquire area to the feeder area (it may not be a different physical area on some Sources).
The application can set this capability to FALSE to use the Source’s non-feeder acquisition area and disallow the further use of feeder capabilities..

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method SetIBitDepth

TTwainSource > Methods > SetIBitDepth

Specifies the pixel bit depths for the Current value of GetIPixelType.

function SetIBitDepth(Value: Word): TCapabilityRet;

Description
For example, when using GetIPixelType returns tbdGray, this capability specifies whether this is 8-bit gray or 4-bit gray by setting 8 or 4 to the value parameter.

This depth applies to all the data channels (for instance, the R, G, and B channels will all have this same bit depth for RGB data).

Comments
The application should loop through all the SetICapPixelType it is interested in and negotiate the BitDepth for each.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method SetICapUnits

TTwainSource > Methods > SetICapUnits

Unless a quantity is dimensionless or uses a specified unit of measure, SetICapUnits sets the unit of measure for all quantities.

type TTwainUnit = (tuInches, tuCentimeters, tuPicas, tuPoints, tuTwips,
tuPixels, tuUnknown);

function SetICapUnits(Value: TTwainUnit): TCapabilityRet;

Description
This method will set the current select unit of measure for the other measures methods using the parameter Value. Note that the source may not support all the unit types. To check if a unit is supported, either check the return of SetICapUnits or use GetICapUnits to obtain all the supported values.

Read more about twain measures here.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method SetImageLayoutFrame

TTwainSource > Methods > SetImageLayoutFrame

Sets the image layout frame.

function SetImagelayoutFrame(const fLeft,fTop,fRight,
fBottom: double): TCapabilityRet;

Description
This method is used to access an special Twain property. This sets the image layout frame (as the method name says)

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method SetIndicators

TTwainSource > Methods > SetIndicators

Enable/disable progress indicators.

function SetIndicators(Value: boolean): TCapabilityRet;

Description
This method enables or disables the progress indicators for the selected twain source.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method SetIPixelFlavor

TTwainSource > Methods > SetIPixelFlavor

Sense of the pixel whose numeric value is zero (minimum data value)..

type TTwainPixelFlavor = (tpfChocolate, tpfVanilla, tpfUnknown);

function SetIPixelFlavor(Value: TTwainPixelFlavor): TCapabilityRet;

Description
Change Value parameter to change pixel flavor capability. Also, for some reason, the source might not support booth (if any) of the pixel flavors. To check if a pixel flavor is supported, either call GetIPixelFlavor using supported param or check the result from this method.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method SetIPixelType

TTwainSource > Methods > SetIPixelType

The type of pixel data that a Source is capable of acquiring (for example, black and white, gray, RGB, etc.)..

type TTwainPixelType = (tbdBw, tbdGray, tbdRgb, tbdPalette, tbdCmy,
tbdCmyk, tbdYuv, tbdYuvk, tbdCieXYZ, tbdUnknown);

function SetIPixelType(Value: TTwainPixelType): TCapabilityRet;

Description
Use this method to set the current pixel type for the image to be transferred. It is probable that the source won't support all the pixel types (it won't return crSuccess in case it don't). Use GetIPixelType to check all the supported pixel types.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method SetIYResolution

TTwainSource > Methods > SetIYResolution

All the Y-axis resolutions the Source can provide.

function SetIYResolution(Value: Extended): TCapabilityRet;

Description
Use SetIYResolution to set the current Y-axis resolution for the source. This value should be in the unit specified by SetICapUnits.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method SetIXResolution

TTwainSource > Methods > SetIXResolution

All the Y-axis resolutions the Source can provide.

function SetIXResolution(Value: Extended): TCapabilityRet;

Description
Use SetIXResolution to set the current X-axis resolution for the source. This value should be in the unit specified by SetICapUnits.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method SetOneValue

TTwainSource > Methods > SetOneValue

Sets the value from any twain capability which only have one value type.

 function SetOneValue(Capability:
        TW_UINT16; ItemType: TW_UINT16;
Value: Pointer): TCapabilityRet;

Description
Use this method to set the value for any twain capability which only have one value type, TW_ONEVALUE. ItemType should contain a TWTY_?? constant for the Value parameter. Value parameter should contain a pointer to a twain variable declared by the application which matches with ItemType.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method SetRangeValue

TTwainSource > Methods > SetRangeValue

Sets the value from any twain capability which uses range values.

 function SetRangeValue(Capability,
        ItemType: TW_UINT16;
Min, Max, Step, Current: TW_INT32): TCapabilityRet;

Description
Use SetRangeValue to set a twain capability which uses TW_RANGE values. Min, Max, Step and Current parameters defines the minimum, maximum, step from a number to next and current which is the actual value.
Range capabilities allows to set uniform steps starting from Min increasing with Step and ending on Max. This capability only allows integer values from twain types smaller than 4 bytes (or 32 bits). Use typecasting in case the value is not an Integer.

Return values
This method returns a TCapabilityRet enumeration to test if it was successful. crSuccess means it worked ok.


method SetupFileTransfer

TTwainSource> Methods > SetupFileTransfer

Sets required information when transfer mode is ttmFile.

 type TTwainFormat = (tfTIFF, tfPict, tfBMP, tfXBM, tfJPEG, tfFPX,
tfTIFFMulti, tfPNG, tfSPIFF, tfEXIF, tfUnknown);

function SetupFileTransfer(Filename: String;
Format: TTwainFormat): Boolean;

Description
This method sets the file information when TransferMode is set to ttmFile. There are two parameters: Filename which is the location of the file you want the source to create and Format which is one of the TTwainFormat formats (Note: it's highly not probable that the source will support all the formats, so try until you reach a valid format, the method will return TRUE).

This method should be called in the event OnSourceSetupFileXfer to work properly.

Return values
If this method returns FALSE, it means either the filename is not a valid filename to be created or, more likely, the format specified is not valid. You may try calling this method again until you find a working combination.

Comments
It is reported that some sources don't return the same file name set here for the event OnSourceSetupFileXfer. For these reason, you might want to store the file you set to try to load when receive OnSourceFileTransfer event in case the filename parameter is not valid.


method UnloadSouce

TTwainSource> Methods > UnloadSource

Unloads the source and set Loaded to FALSE.

function UnloadSource(): Boolean;

Description
This method tells Twain to unload the source from memory and it setting the Loaded property to FALSE.

Return values
Returns TRUE or FALSE if it was successfully unloaded or not.


How to acquire an image

Delphi twain component > Tutorial on how to acquire an image

The need for the component
Since the component registers itself in Delphi component palette, the first thing you must do is to select the component in Delphi palette and click in the desired form to add it.

Editing the first properties in the property editor
With the component inserted, you must set some properties to tell Twain interface about this application. This can be done by:

  1. Selecting the component in the form to display it's properties in the property editor, which is normally on the left side of the screen
  2. Double clicking in the “Info” property which will expand it and display it's sub-properties
  3. Fill each property. Descriptions:
Country code | Current country code. Example, Brazil country code is 55, USA is 1
Groups | Unless you indend using an device with audio support, we recommend letting it as it is
Language | You may leave tlUserLocale to use Windows current version, or select an appropriate language on the list. The reason for this is that some sources may provide a different language for the interface.
Majorversion | Application major version (ex, 1 from 1.5)
Manufacturer | Application manufacturer
Minorversion | Application major version (ex, 5 from 1.5)
ProductFamily | Name of the application product family, ex Office
ProductName | Name of the application
VersionInfo | Version description

Also, the component support one two three different transference modes. Their differences and characteristics are better explained in this page.
For this tutorial, we'll be using Memory transference, which is the best for larger images, and also the default one.

As default, it should be already selected, but if you want to make sure, check if the TransferMode property in the object inspector is set to ttmMemory.

Adding an image container to hold the image and a button
In order to the final user preview the image, you may add an TImage component on the main form. It's located on the Additional tab in delphi component palette. Also, you should add a TButton (standard page) control anywhere in the form which will be the trigger to acquire the images.

Preparing the event to handle the received image
After the image was sucessfully retrieved, an event will be called with the image object or handle. This event is called OnImageAcquire and will be edited by clicking on the “Events” tab on the property editor and double clicking on OnImageAcquire. Put the following code there:

procedure DelphiTwain1.OnTwainAcquire(Sender: TObject; const Index: Integer; Image: TBitmap; var Cancel: Boolean);
begin
  //Copies the acquired bitmap to the TImage control
  Image1.Picture.Assign(Image);
  //Because the component supports multiple images
  //from the source device, Cancel will tell the
  //source that we don't want no more images
  Cancel := TRUE;
end;

Setting to allow user to acquire the image
When the user click over the button, a dialog to allow the user to choose a source should be displayed, and if the user selects a source on it and presses ok, the final image should be acquired.

To do so, we should edit the button OnClick event. In the design time, click on the button once, click on the events tab on the Object Inspector and then double-click over the OnClick event. Using the source code editor, put the following code:

procedure Button1.OnClick(Sender: TObject);
var
  SourceIndex: Integer;
  Source: TTwainSource;
begin
  //Make sure that the library and Source Manager
  //are loaded
  DelphiTwain1.LibraryLoaded := TRUE;
  DelphiTwain1.SourceManagerLoaded := TRUE;
  //SelectSource method displays a common Twain dialog
  //to allow the user to select one of the avaliable
  //sources and returns it's index or -1 if either
  //the user pressed Cancel or if there were no sources
   SourceIndex := DelphiTwain1.SelectSource();
  if (SourceIndex <> -1) then
  begin
     //Now that we know the index of the source, we'll
     //get the object for this source
     Source := DelphiTwain1.Source[SourceIndex];
     //Load source and acquire image
     Source.Loaded := TRUE;
     Source.Enabled := TRUE;
  end {if (SourceIndex <> -1)}
end;

Test the results
Done, now all you must do is test what you have done:

  1. Run the project
  2. Click over the button
  3. In the dialog, select one of the sources
  4. Click over the Ok button

The image control now should contain the image that the source just acquired.


Tutorial on how to retrieve and set twain capabilities

This component implements lots of twain capabilities to simplify the process of getting and setting it's values. Unfortually there are far too many capabilities to handle.

For this reason, this component also implements a few method to handle all the capabilities from twain, these are:

  • GetOneValue / SetOneValue
  • GetRangeValue / SetRangeValue
  • GetEnumerationValue / SetEnumerationValue
  • GetArrayValue / SetArrayValue

After you understand them, it's fairly simple to use this methods.

The explanation
What are the twain capabilities ?

One of TWAIN’s benefits is it allows applications to easily interact with a variety of acquisition devices. Devices can provide image or audio data. For instance,

  • Some devices have automatic document feeders.
  • Some devices are not limited to one image but can transfer multiple images.
  • Some devices support color images.
  • Some devices offer a variety of halftone patterns.
  • Some devices support a range of resolutions while others may offer different choices.
  • Some devices allow the recording of audio data associated with an image.

All these items may be negotiated with the source (using the source manager) using capabilities, which are properties which the application may set and retrieve from the source.

Source supporting the capabilities

Not all the sources support all the capabilities, also, some capabilities from a certain source may not support all the features specified by twain specification. For this reason, the component also supports checking these booth cases using the TCapabilityRet enumeration. All the methods specified above, and predefined capability setting methods from the component returns a TCapabilityRet. If the method returns:

  • crSuccess - Everything went ok
  • crUnsupported - Capability not supported by the source
  • crBadOperation - Bad combination of values from the parameters, a feature from the capability may not be supported
  • crDependencyError - Capability depends on another capability which is not properly set
  • crLowMemory - The system is short on memory
  • crInvalidState - The source or the source manager are not ready to set this capability or do the requested operation

Capabilities containers

A capability in twain also may be of different types:

  • One value - Capability contains only one value
  • Range - Capability specifies a range by providing the first number in the range, step, which is the distance from the next item, and the final item. This may be useful for capabilities as brightness, or quality allowing for instance values as (0, 10, 20..90, 100)
  • Enumeration - Provides a list of related values, also providing the current and default values from the list
  • Array - Provides a list of not directly related values

Value types

Twain values, as in delphi, may have different types. Read more those at Different Twain Types page.

What are the capabilities

They are all specified in twain specification, which can be retrieved at twain website at: http://www.twain.com.

The action, manually setting values
One-value types, retrieving

The first thing you must do, is declare the used variables:
var
  ItemType: TW_UINT16;
  Value: String;
  Return: TCapabilityRet;

Now, call the GetOneValue:
  Return := DelphiTwain1.Source[0].GetOneValue(CAP_PRINTERENABLED,
  ItemType, Value, rcGet);
GetOneValue method will then call twain to return the value from this capability. If it was successful (Return = crSuccess), the method will fill ItemType parameter with the twain type returned by twain. Also, GetOneValue will fill Value parameter with the value returned.

The reason for Value being a string type, is because it is the only delphi type that can hold all the other twain types. Using ItemType returned, the application is able to convert from string to any type it needs.

  if (Return <> crSuccess) then
  begin
    ShowMessage('This capability is not supported');
    exit;
  end;

In this case, ItemType must be a twain boolean type, otherwise the source was written wrong:

  if (ItemType <> TWTY_BOOL) then
  begin
    ShowMessage('The source does not support this ' +
      'capability properly.');
    exit;
  end;

Boolean have value 1 if TRUE and other than 1 if FALSE. Knowing this, we are ready to check the return value:

  if StrToIntDef(Value, 0) = 1 {value = '1'} then
    ShowMessage('TRUE')
  else
    ShowMessage('FALSE');

One-value types, setting

Setting, is easier than retrieving, but it is also different. Because you already know the twain type to use, you should declare it:

var
  Value: TW_BOOL;
  Return: TCapabilityRet;

Now, call SetOneValue to set this value using a pointer to the value variable.

  Return := DelphiTwain1.Source[0].SetOneValue(
     TWTY_BOOL, @Value);
  if Return <> crSuccess then
    ShowMessage('This capability is not supported');

Multiple value types, retrieving

The difference between multiple value and one-values is that multiple values uses arrays to retrieve the values:

var
List: TGetCapabilityList;
ItemType: TW_UINT16;
Return:
        TCapabilityRet;
i, Current, Default: Integer;
Values: Array of Word {or TW_UINT16};
CurrentValue, DefaultValue: Integer;
begin
Return := DelphiTwain1.Source[0].GetEnumerationValue(
ICAP_BITDEPTH, ItemType, List, Current, Default,
rcGet);

if (Return <> crSuccess) then
begin
ShowMessage('This capability is not supported');
exit;
end;
if
        (ItemType <> TWTY_UINT16) then
begin
ShowMessage('The source does not support this
        ' +
'capability properly.');
exit;
end;

SetLength(Values, Length(List));
FOR i := 0 TO Length(List) - 1 DO
Values[i] := StrToInt(List[i]);
CurrentValue := Values[Current];
DefaultValue := Values[Default];
end;

Setting, is also easier:

const
  ListWord: Array [0..2] of TW_UINT16 = (1, 4, 8);
  Current = 1;
var
  List: TSetCapabilityList;
  i: Integer;
  Return: TCapabilityRet;
begin
  for i := 0 to 2 DO
    List[i] := @ListWord[i];
  Return := DelphiTwain1.Source[0].SetEnumerationValue(
    ICAP_BITDEPTH,  TWTY_UINT16, Current, List);
  if Return <> crSuccess then
    ShowMessage('This capability is not supported');
end;


Tutorial on how to directly call Twain

The TDelphiTwain component itself handle most of twain features making it real easy to the application use twain. Some source may provide some methods which are not specified in twain latest specification. For this reason, the component provides direct access to twain features.

Twain features may be directly accessed using the property TwainProc. This property will contain a pointer to twain main procedure after the library is loaded.

1 Including twain unit in the uses clause

Check including twain in the uses.

2 Loading the library

TwainProc will only contain a valid pointer after the library is loaded for obvious reasons. For this reason you must load the library by setting LibraryLoaded to TRUE or calling LoadLibrary.

3 Load source manager

After the library is loaded, TwainProc will contain a valid pointer and will be ready to be used. But most of the methods needs the source manager to be loaded. To do so, either set SourceManagerLoaded to TRUE or call LoadSourceManager.

4 Calling the method

The method may be called as bellow:

TwainProc = function(pOrigin:
        pTW_IDENTITY;
pDest: pTW_IDENTITY; DG: TW_UINT32; DAT: TW_UINT16;
MSG: TW_UINT16; pData: TW_MEMREF): TW_UINT16; stdcall;

  • pOrigin - A pointer to a TW_IDENTITY structure with information from the current application. Info property handle this structure and AppIdentity returns a pointer to the TW_IDENTITY from the Info property. So in this parameter put AppIdentity.
  • pDest - If you intend to send a message to the source manager,
    use nil for this parameter, if you intend to send directly to a source, place a pointer to the source pTW_IDENTITY by setting this value to the SourceIdentity property from any TTwainSource object.
  • DG - Control group to send this message, DG_CONTROL, DG_IMAGE and DG_AUDIO. Depends on the kind of message.
  • DAT - Another group parameter to identity the message
  • MSG - Message to send to twain
  • pData - Pointer depending on the combination of DG/DAT/MSG

Twain defines hundreds of different messages to send to the source and source manager. They are all definied in their specification which might be obtained in their web-site: http://www.twain.com.

5 Return values

The method returns different return values, specified in Twain special error returns.


Different twain types

To allow the library to be used in different compilers, twain introduce some new types which the application needs to understand. The types are definied in twain.pas unit, which should be included in the uses clause. All this types have equivalent types for delphi listed bellow:

String types
The types bellow allows holding text information:

Twain type | Delphi equivalent | Type constant
TW_STR32 | array[0..33] of Char | TWTY_STR32
TW_STR64 | array[0..65] of Char | TWTY_STR64
TW_STR128 | array[0..129] of Char | TWTY_STR128
TW_STR255 | array[0..255] of Char | TWTY_STR255
TW_STR1024 | array[0..1025] of Char | TWTY_STR1024
TW_UNI512 | array[0..511] of WideChar | TWTY_UNI512

Convertion from TW_STR?? to a string is made automatically by delphi. To convert from a string to TW_STR??, you may create a method using the following example bellow:

{Puts a string inside a TW_STR255}
function StrToStr255(Value: String): TW_STR255;
begin
  {Clean result}
  Fillchar(Result, sizeof(TW_STR255), #0);
  {If value fits inside the TW_STR255, copy memory}
  if Length(Value) <= sizeof(TW_STR255) then
    CopyMemory(@Result[0], @Value[1], Length(Value))
  else CopyMemory(@Result[0], @Value[1],
     sizeof(TW_STR255));
end;

Numeric types
Allows holding numbers and logical information

Twain type | Delphi equivalent | Type constant | Description
TW_INT8 | shortint | TWTY_INT8 | signed 8-bit
TW_INT16 | smallInt | TWTY_INT16 | signed 16-bit
TW_INT32 | Longint | TWTY_INT32 | signed 32-bit
TW_UINT8 | byte | TWTY_UINT8 | unsigned 8-bit
TW_UINT16 | word | TWTY_UINT16 | unsigned 16-bit
TW_UINT32 | cardinal | TWTY_UINT32 | unsigned 32-bit

Fixed point structures
Allows holding numbers and logical information

Twain type Delphi equivalent Type constant Description
TW_FIX32
 TW_FIX32 = record
Whole: TW_INT16;
Frac: TW_UINT16;
end; 		TWTY_FIX32 Fixed point structure.


TCapabilityRet explanation

TCapabilityRet is a translation from twain return to the component set from a call to set one of twain properties or capabilities. The values are:

  • crSuccess - Everything went ok
  • crUnsupported - Capability not supported by the source
  • crBadOperation - Bad combination of values from the parameters.
  • crDependencyError - Capability depends on another capability which is not properly set
  • crLowMemory - The system is short on memory
  • crInvalidState - The source or the source manager are not ready to set this capability or do the requested operation
  • crInvalidState - The container used is invalid


Twain Sources

The source is responsible for dealing with the device hardware. It communicates with the application using the source manager. The Source provides the translation from TWAIN operations and interactions with the Source’s user interface into the equivalent commands for the device driver that cause the device to behave as desired.

Twain sources are implemented as windows libraries (except with extension .ds) and are located in Windows\twain_32 directory (for 32 bits Windows)
An application never communicates directly with the user, it uses the source manager for this.

The Source receives operations either from the application, via the Source Manager, or directly from the Source Manager. It processes the request and returns the appropriate Return Code indicating the results of the operation to the Source Manager.

Every TWAIN-compliant Source provides a user interface specific to its particular device. When the application user selects the Acquire option, the Source’s User Interface may be displayed. If desired, the application can write its own version of this interface, too.


Include twain unit in the uses

Calling twain directly requiries different types. These types are implemented in C using a header file called twain.h, and it is translated to pascal by Project JEDI, an international community of Delphi developers. The translated twain.h is included with this component in the file twain.pas.

If you intend making direct calls to twain using TwainProc method, you should include twain in the units clause (Top of the main unit):

uses
  Windows, forms, classes, sysutils, graphics,
  twain {include twain unit in the uses};

Also, delphi must be able to find this unit to use it. To do so, you must include the component directory in Delphi search path. Follow the following steps:

  • Go to the Delphi Tools menu and click on the first item, Enviroment Options.
  • In the window that will show up, select the page Library
  • In the Library Path field add the component directory by editing the control and adding a ; symbol, followed by the component path, for instance: ;c:\progra~1\gustav~1\twain\
  • Click OK


Twain special error returns

Twain returns different error values constants. They are definied in twain unit which should be included in the uses. These errors are returned in two different ways: by the event OnAcquireError, in the ErrorCode parameter (and Additional which is equivalent to GetReturnStatus bellow). And by directly calling twain. The return constants are bellow:

  • TWRC_SUCCESS - Everything worked ok
  • TWRC_FAILURE, TWRC_CHECKSTATUS - Something went wrong. Also there is extended error information which can be retrieved when pDest is not nil calling the TTwainSource GetReturnStatus method.
  • TWRC_CANCEL - User cancelled the transference

GetReturnStatus (and Additional parameter for OnAcquireError) returns another set of error constants:

  • TWCC_SUCCESS - It worked!
  • TWCC_BUMMER - Failed for unknown causes
  • TWCC_LOWMEMORY - Low memory avaliable
  • TWCC_NODS - No source definied
  • TWCC_DSMAXCONNECTIONS - Source already reached the maximum number of connections
  • TWCC_OPERATIONERROR - Source or Source Manager reported an error, application shouldn't
  • TWCC_BADCAP - Unknown capability
  • TWCC_BADPROTOCOL - Unknown MSG DG DAT combination
  • TWCC_BADVALUE - Data parameter out of range
  • TWCC_SEQERROR - DG DAT MSG out of sequence
  • TWCC_BADDEST - Unknown application/source in the parameters
  • TWCC_CAPUNSUPPORTED - Capability not supported by the source
  • TWCC_CAPSEQERROR - Capability has dependancy on other capability
  • TWCC_DENIED - File system operation is denied
  • TWCC_FILEEXISTS - Failed because the file already exists
  • TWCC_FILENOTFOUND - The file does not exists
  • TWCC_NOTEMPTY - Failed because the directory is not empty
  • TWCC_PAPERJAM - The feeder is jammed
  • TWCC_PAPERDOUBLEFEED - The feeder detected multiple pages
  • TWCC_FILEWRITEERROR - Error writing the file (disk full, etc)
  • TWCC_CHECKDEVICEONLINE - Device went offline prior the operation


Country codes

Country codes values

Bellow are the definied country codes for the component:

AFGHANISTAN
        = 1001;
ALGERIA = 213;
AMERICANSAMOA = 684;
ANDORRA = 033;
ANGOLA = 1002;
ANGUILLA = 8090;
ANTIGUA = 8091;
ARGENTINA = 54;
ARUBA = 297;
ASCENSIONI = 247;
AUSTRALIA = 61;
AUSTRIA = 43;
BAHAMAS = 8092;
BAHRAIN = 973;
BANGLADESH = 880;
BARBADOS = 8093;
BELGIUM = 32;
BELIZE = 501;
BENIN = 229;
BERMUDA = 8094;
BHUTAN = 1003;
BOLIVIA = 591;
BOTSWANA = 267;
BRITAIN = 6;
BRITVIRGINIS = 8095;
BRAZIL = 55;
BRUNEI = 673;
BULGARIA = 359;
BURKINAFASO = 1004;
BURMA = 1005;
BURUNDI = 1006;
CAMAROON = 237;
CANADA = 2;
CAPEVERDEIS = 238;
CAYMANIS = 8096;
CENTRALAFREP = 1007;
CHAD = 1008;
CHILE = 56;
CHINA = 86;
CHRISTMASIS = 1009;
COCOSIS = 1009;
COLOMBIA = 57;
COMOROS = 1010;
CONGO = 1011;
COOKIS = 1012;
COSTARICA = 506 ;
CUBA = 005;
CYPRUS = 357;
CZECHOSLOVAKIA = 42;
DENMARK = 45;
DJIBOUTI = 1013;
DOMINICA = 8097;
DOMINCANREP = 8098;
EASTERIS = 1014;
ECUADOR = 593;
EGYPT = 20;
ELSALVADOR = 503;
EQGUINEA = 1015;
ETHIOPIA = 251;
FALKLANDIS = 1016;
FAEROEIS = 298;
FIJIISLANDS = 679;
FINLAND = 358;
FRANCE = 33;
FRANTILLES = 596;
FRGUIANA = 594;
FRPOLYNEISA = 689;
FUTANAIS = 1043;
GABON = 241;
GAMBIA = 220;
GERMANY = 49;
GHANA = 233;
GIBRALTER = 350;
GREECE = 30;
GREENLAND = 299;
GRENADA = 8099;
GRENEDINES = 8015;
GUADELOUPE = 590;
GUAM = 671;
GUANTANAMOBAY = 5399;
GUATEMALA = 502;
GUINEA = 224;
GUINEABISSAU = 1017;
GUYANA = 592;
HAITI = 509;
HONDURAS = 504;
HONGKONG = 852 ;
HUNGARY = 36;
ICELAND = 354;
INDIA = 91;
INDONESIA = 62;
IRAN = 98;
IRAQ = 964;
IRELAND = 353;
ISRAEL = 972;
ITALY = 39;
IVORYCOAST = 225 ;
JAMAICA = 8010;
JAPAN = 81;
JORDAN = 962;
KENYA = 254;
KIRIBATI = 1018;
KOREA = 82;
KUWAIT = 965;
LAOS = 1019;
LEBANON = 1020;
LIBERIA = 231;
LIBYA = 218;
LIECHTENSTEIN = 41;
LUXENBOURG = 352;
MACAO = 853;
MADAGASCAR = 1021;
MALAWI = 265;
MALAYSIA = 60;
MALDIVES = 960;
MALI = 1022;
MALTA = 356;
MARSHALLIS = 692;
MAURITANIA = 1023;
MAURITIUS = 230;
MEXICO = 3;
MICRONESIA = 691;
MIQUELON = 508;
MONACO = 33;
MONGOLIA = 1024;
MONTSERRAT = 8011;
MOROCCO = 212;
MOZAMBIQUE = 1025;
NAMIBIA = 264;
NAURU = 1026;
NEPAL = 977;
NETHERLANDS = 31;
NETHANTILLES = 599;
NEVIS = 8012;
NEWCALEDONIA = 687;
NEWZEALAND = 64;
NICARAGUA = 505;
NIGER = 227;
NIGERIA = 234;
NIUE = 1027;
NORFOLKI = 1028;
NORWAY = 47;
OMAN = 968;
PAKISTAN = 92;
PALAU = 1029;
PANAMA = 507;
PARAGUAY = 595;
PERU = 51;
PHILLIPPINES = 63;
PITCAIRNIS = 1030;
PNEWGUINEA = 675;
POLAND = 48;
PORTUGAL = 351;
QATAR = 974;
REUNIONI = 1031;
ROMANIA = 40;
RWANDA = 250;
SAIPAN = 670;
SANMARINO = 39;
SAOTOME = 1033;
SAUDIARABIA = 966;
SENEGAL = 221;
SEYCHELLESIS = 1034;
SIERRALEONE = 1035;
SINGAPORE = 65;
SOLOMONIS = 1036;
SOMALI = 1037;
SOUTHAFRICA = 27 ;
SPAIN = 34;
SRILANKA = 94;
STHELENA = 1032;
STKITTS = 8013;
STLUCIA = 8014;
STPIERRE = 508;
STVINCENT = 8015;
SUDAN = 1038;
SURINAME = 597;
SWAZILAND = 268;
SWEDEN = 46;
SWITZERLAND = 41;
SYRIA = 1039;
TAIWAN = 886;
TANZANIA = 255;
THAILAND = 66;
TOBAGO = 8016;
TOGO = 228;
TONGAIS = 676;
TRINIDAD = 8016;
TUNISIA = 216;
TURKEY = 90;
TURKSCAICOS = 8017;
TUVALU = 1040;
UGANDA = 256;
USSR = 7;
UAEMIRATES = 971;
UNITEDKINGDOM = 44;
USA = 1;
URUGUAY = 598;
VANUATU = 1041;
VATICANCITY = 39;
VENEZUELA = 58;
WAKE = 1042;
WALLISIS = 1043;
WESTERNSAHARA = 1044;
WESTERNSAMOA = 1045;
YEMEN = 1046;
YUGOSLAVIA = 38;
ZAIRE = 243;
ZAMBIA = 260;
ZIMBABWE = 263;


What is the source manager

The Source Manager provides the communication path between the application and the Source, supports the user’s selection of a Source, and loads the Source for access by the application.
The majority of operation requests are initiated by the application and flow to the Source Manager and Source. The Source, via the Source Manager, is able to pass back data and Return Codes.It is implemented by the Twain library included since Windows 98 but also avaliable as a separeted download.


Common capabilities

Most common capabilities

TWAIN defines over 150 different capabilities. Although the number may seem overwhelming, it is easier to handle if you recognize that some of the capabilities are more commonly used. Here are some of these capabilities:

Basic Capabilities
Units capabilities
The GetICapUnits/SetICapUnits are used to return/set the unit of measure which will be used by the Source. The default is inches but centimeters, pixels, etc. are alowed. This capability is used when measuring several other capabilities, including:

GetIYResolution
SetIYResolution
All the Y-axis resolutions the Source can provide.
GetIXResolution
SetIXResolution
 All the X-axis resolutions the Source can provide.
GetIPhysicalWidth
 The maximum physical width (X-axis) the Source can acquire.
GetIPhysicalHeight
 The maximum physical height (Y-axis) the Source can acquire.

Sense of the Pixel
The SetIPixelFlavor/GetIPixelFlavor specifies how a bit of data should be interpreted when transferred from Source to application. The default is tpfChocolate which means a 0 indicates black (or the darkest color). The alternative, tpfVanilla, means a 0 indicates white (or the lightest color).

Resolution
To inquire or set the Source’s resolution, use GetIXResolution / SetIXResolution and GetIXResolution / SetIXResolution

Image Type Capabilities
Types of Pixel
The application should negotiate GetIPixelType/SetIPixelType and GetIBitDepth/SetIBitDepth unless it can handle all pixel types at all bit depths. The allowed pixel types are: tbdBW, tbdGRAY, tbdRGB, tbdPALETTE, tbdCMY, tbdCMYK, tbdYUV, tbdYUVK, and tbdCIEXYZ.

Depth of the Pixels (in bits)
A pixel type such as tbdBW allows only 1 bit per pixel (either black or white). The other pixel types may allow a variety of bits per pixel (4-bit or 8-bit gray, 8-bit or 24-bit color). Be sure to set using the SetIPixelType first, then use the SetIBitDepth.

Parameters for Acquiring the Image
Exposure
Several capabilities can influence this. They include ICAP_BRIGHTNESS, ICAP_CONTRAST, ICAP_SHADOW, ICAP_HIGHLIGHT, ICAP_GAMMA, ICAP_AUTOBRIGHT.

Scaling
To instruct a Source to scale an image before transfer, refer to ICAPXSCALING and ICAP_YSCALING.

Rotation
To instruct a Source to rotate the image before transfer, refer to ICAP_ROTATION and ICAP_ORIENTATION.


About Twain

Delphi twain component > About Twain

What is the TWAIN Initiative?
The TWAIN initiative was originally launched in 1992 by leading industry vendors who recognized a need for a standard software protocol and applications programming interface (API) that regulates communication between software applications and imaging devices (the source of the data). TWAIN defines that standard. The three key elements in TWAIN are the application software, the Source Manager software and the Data Source software. The application uses the TWAIN toolkit which is shipped for free.

Why do you need Twain ?
For many years, the computer industry lacked some efficient way to implement support to acquire devices such as scanners, fax-modems. The problem was that every time a new device was released, the applications needed to be update to support it. For this reason, Twain first draft was released in 1992 and later packed with Windows 98. Twain provides a common interface to access such devices. The device takes the responsibility to provide access to the content and Twain interface to properly communicate with the application.

What supports Twain ?
Most of scanners (not to say all), webcams, some fax modems, database engines, digital cameras, and more. With twain, they are all in reach with the application.

About this component
It's not easy implement to implement Twain since it needs to modify the application loop, communicate with the source manager, with the source and understand the incoming images. For this reason this component was created. Using it doesn't takes more than a few lines of code to get most of Twain features.


Different transfer modes

Transference modes

What is a transference mode ?
Twain specification defines that currently, three different transference modes are available, file, native handle and memory. Transference mode is simply that way that the source (scanner/camera, etc) driver will transfer the acquired image to the destination application.

So why not just one transference mode ?
Which one of the transference modes has it's advantages and drawbacks:

  • Native handle - All the sources must support this transference mode. This mode transfer the image from the source to the application using a windows BITMAP handle structure. The major advantage for this mode is that it is the easiest to implement.
    Advantage: is that it is not recommended for really large images
    Drawback: because it allocates once memory for all the image, which can get quite large.
  • File - It's optional, but recommended, for the source to support this. This transference mode tells the source to create a disk file in a place designed by the application with the acquired image.
    Advantage: Ideal for transferring large images and also support multiple formats, depending on the source.
    Drawback: Slower, because the application needs to reread the file and it needs disk space to store it

  • Memory transfer - Every source must support it. The image is transferred through blocks of allocated data and the application needs to interpretate the bitmap.
    Advantage: Offers the greatest flexibility, both in data capture and control. No need to allocate large blocks of memory.
    Drawback: It is the least simple to implement making hard to support all the files formats included in the source device.

Conclusion
For larger images, which will exceed RAM memory in size, it's recommended the file transference mode. For not so large images, choose between Memory or Native transfer (recommenced is memory transfer).


Obtaing twain library

Twain library is included with Windows 98 version and later. For Windows 95, you must install it manually in order to Twain to work.

Check that the following files are being installed. Check their version. If the version you are trying to install is later, overwrite the existing file.

  • TWAIN.DLL installed in the \WINDOWS directory
  • TWAIN_32.DLL installed in the \WINDOWS directory
  • TWUNK_16.EXE installed in the \WINDOWS directory
  • TWUNK_32.EXE installed in the \WINDOWS directory

If installing on a Win32s platform, then install MSVCRT20.DLL for Win32s in the \WINDOWS\SYSTEM directory if a later version isn't already installed. Replace any version that has the same or earlier version number.

If installing on a Windows 95 platform, then MSVCRT20.DLL for Windows
95 will have been shipped with the system. No other installation is necessary beyond the four TWAIN and TWUNK files.

These files should be included with the component, or provided in the homepage. To get the latest versions, try Twain homepage at:
http://www.twain.com


Twain measures

Twain provides a measure capability to set the length measure type for some of the capabilities. The component wraps this measure capability using the methods GetICapUnits and SetICapUnits. Possible values for this two methods are:

  • tuInches - Measure unit
  • tuCentimeters - Multiply by 0.394 to get one inche
  • tuPicas - a bit less than 1/6 inch
  • tuPoints - equal to 0.0138889 inche
  • tuTwips - One twip is equal to 1/1440 inch
  • tuPixels - Use windows API GetDeviceCaps(LOGPIXELS?) to convert between inches and pixels.


GetOneValue/SetOneValue example

To this example to work, create the twain component (TDephiTwain) in the main form and create your own code to load the library (LibraryLoaded parameter), source manager (SourceManagerLoaded), select a source (Source[Index: Integer]) and load it (Loaded). This example will handle ICAP_HIGHLIGHT capability from twain by providing two methods, one to get the value and the other to set.

uses
  Windows,....,twain;

Also, be sure to include twain unit in uses.

 {Convert
        from extended to Fix32}
function FloatToFix32 (floater: extended): TW_FIX32;
var
fracpart : extended;
begin
//Get numerical part by truncating the
        float number
Result.Whole := trunc(floater);
//Get fractional part by subtracting
        float number by
//numerical part. Also we make sure
        the number is not
//negative by multiplying by -1 if it is negative
fracpart := floater - result.Whole;
if fracpart < 0 then fracpart := fracpart * -1;
//Multiply by 10 until there is no fractional
while FracPart - trunc(FracPart) <> 0 do
fracpart := fracpart * 10;
//Return fractional part
Result.Frac := trunc(fracpart);
end;

function SetIHighlight(Source: TTwainSource;
Value: Extended): TCapabilityRet;
var
fix32: TW_FIX32;
begin
//The extended parameter must be converted
        to
//TW_FIX32 twain record
fix32 := floattofix32(Value);
Result := Source.SetOneValue(ICAP_HIGHLIGHT,
TWTY_FIX32, @fix32);
end;

function GetIHighlight(Source:
        TTwainSource;
var Return: Extended; Mode: TRetrieveCap = rcGet):
TCapabilityRet;

var
  Value: String;
  ItemType: TW_UINT16;
begin
  Result := Source.GetOneValue(ICAP_HIGHLIGHT,
    ItemType, Value, Mode);
  //The itemtype must be TWTY_FIX32
  if (Result = crSuccess) and
     (ItemType <> TWTY_FIX32) then
    Result := crUnsupported;
  //If everything went ok
  if (Result = crSuccess) then
     Return := StrToFloat(Value);
end;

To use the methods GetIHighlight and SetIHighlight, set Source as a TTwainSource object retrieved with Source[Index: Integer] . It's important that the source must be loaded before calling these.


Example using file transference

In order to run this example, create a new application (File > New Application). In the new created form, add a TButton and TDelphiTwain component anywhere in the form.

Double-click on the button to edit the OnClick event:

procedure TForm1.Button1Click(Sender: TObject);
var
  SourceIndex: Integer;
begin
  //Try loading the library
  if DelphiTwain1.LoadLibrary then
  begin

    //Same as SourceManangerLoaded := TRUE
    DelphiTwain1.LoadSourceManager();
    //Select the source
    SourceIndex := DelphiTwain1.SelectSource();
    if SourceIndex <> -1 then
      with DelphiTwain1.Source[SourceIndex] do
      begin

        //Prepare for transfering using ttmFile mode
        Loaded := TRUE;
        TransferMode := ttmFile;
        Enabled := TRUE;

      end else ShowMessage('Cancelled')

  end
  else ShowMessage('Twain not installed')
end;

Now edit TDelphiTwain events OnSourceSetupFileXfer and OnSourceFileTransfer:

procedure TForm1.DelphiTwain1SourceSetupFileXfer   (Sender: TObject; const Index: Integer);
begin
  delphitwain1.source[index].SetupFileTransfer(
    IncludeTrailingBackslash(getcurrentdir) +
    'image.bmp',tfBMP);
end;

procedure TForm1.DelphiTwain1SourceFileTransfer(
  Sender: TObject; const Index: Integer;
  Filename: TW_STR255; Format: TTwainFormat;
  var Cancel: Boolean);
begin
  ShowMessage('File saved to ' + filename);
end;


Example using GetCapabilityRec

The example bellow is a good example to use the combination of GetCapabilityRet and Get???value methods. To use it, replace ICAP_?? by the capability desired.

var
  Handle: HGLOBAL;
  Container: TW_UINT16;
  ItemType: TW_UINT16;
  Value: String;
  List: TGetCapabilityList;
  Min, Max, Step, DefaultStr, CurrentStr: String;
  Current, Default: Integer;
begin
  GetCapabilityRec(ICAP_??, Handle, rcGet, Container);
  case Container of
    TWON_ONEVALUE:
      if GetOneValue(ICAP_??, ItemType, Value, rcGet,
        Handle) then {Do action...}
    TWON_ENUMERATION:
      if GetEnumerationValue(ICAP_??, ItemType, List,
        Current, Default, rcGet, Handle) then {Action}
    TWON_ARRAY:
      if GetArrayValue(ICAP_??, ItemType, List,         rcGet, Handle) then {Do action...}
    TWON_RANGE:
      if GetRangeValue(ICAP_??, ItemType, List,
        Min, Max, Step, DefaultStr, CurrentStr,
        rcGet, Handle) then {Do action...}
  end {case};
end;


Example using event OnTwainAcquire and Enabled property

This event receives the final images when transference mode is set to ttmNative or ttmMemory (transfermode property). To run this example, create a new application (File > New Application) and add a TImage, a TButton and a TDelphiTwain component in the form.

When the user clicks over the button, it will acquire image from the first twain source avaliable. To do so, double-click over the TButton control to edit the event.

procedure TForm1.Button1Click(Sender:
        TObject);
begin
//Loads library and source manager.
        In case the
//LibraryLoaded value continues to be FALSE, it
//means that twain is not installed, so exit
DelphiTwain1.LibraryLoaded := TRUE;
DelphiTwain1.SourceManagerLoaded := TRUE;
if DelphiTwain1.LibraryLoaded = FALSE then
        Exit;
//If there is no sources, also exit
if DelphiTwain1.SourceCount = 0 then exit;

//Acquire from the first source
DelphiTwain1.Source[0].TransferMode := ttmMemory;
DelphiTwain1.Source[0].Loaded := TRUE;
DelphiTwain1.Source[0].Enabled := TRUE;
end;

Also edit
          TDelphiTwain
        component OnTwainAcquire
        event:

procedure TForm1.DelphiTwain1TwainAcquire(
Sender: TObject; const Index: Integer;
Image: TBitmap; var Cancel: Boolean);
begin
//Copies the Image parameter to
        the TImage
Image1.Picture.Assign(Image);
//We only want the first image
Cancel := TRUE;
end;

Now, execute the application and click over the TButton control.


Example on how to use SelectSource

It is simple to use the SelectSource method. To test this example, create a new application (File > New Application). In this newly created form add the TDelphiTwain component and also a TButton anywhere in the form.
Double click over the TButton to edit the OnClick event:

procedure TForm1.Button1Click(Sender: TObject);
var
  SelItem: Integer;
begin
  //Loads the library and the source manager
  if DelphiTwain1.LoadLibrary() then
    with DelphiTwain1 do
    begin
      LoadSourceManager();
      SelItem := SelectSource();
      //If no item was selected, show message
      if SelItem = -1 then
        ShowMessage('No item was chosen')
      else
        ShowMessage(Source[SelItem].ProductName);
    end
  else ShowMessage('Twain is not installed');
end;

Now run the project and click on the button. Try selecting an item and pressing ok or pressing cancel.


Example for the property Source[Index: Integer]

To use this example, you should create a new delphi project (File > New Application). Inside the new application insert a listbox control which will hold the source list. Also, add a TDelphiTwain component anywhere in the current form. Edit OnCreate event for the form:

procedure TForm1.FormCreate(Sender: TObject);
var
  i: Integer;
begin
  with DelphiTwain1 do
  begin
    //Booth library and source manager must be loaded
    LibraryLoaded := TRUE;
    if LibraryLoaded = TRUE then
    begin
      SourceManagerLoaded := TRUE;
      //Enumerate sources
      FOR i := 0 TO SourceCount - 1 DO
        Listbox1.Items.Add(Source[i].ProductName);
    end
    else
      ShowMessage('Twain is not installed');
  end
end;

Now, after you execute the project, the listbox control should contain the list of all the sources avaliable.


Component in the web

Installing the component (Delphi)

The component is installed as any other common delphi component.
  1. First of all, copy (unzip) all the files to any directory. The obj sub-directory is necessary to install the component.
  2. Run a Borland Delphi instance
  3. Go to the menu Component and select Install Component item as shown in the picture bellow:
  4. In the "Unit file name:" field, click on "Browse..." and point to the files DelphiTwain.Pas, DelphiTwainUtils.Pas, Twain.Pas.
    (Multiple files may be selected using the CTRL key)
    By default Delphi will install in the "Borland User Components" package, it might be changed using "Package file name" field or "Into new package" page.
    Click on Ok
  5. A confirmation dialog will be shown asking if you want to build the package (name might change depending on Delphi version). Click on "Yes".
  6. You have just installed DelphiTwain, now close the package window (Don't forget to put "Yes" when it ask if you want to save the package).

You may also want to add the unit to the search path.

  1. This time, go to the "Tools" menu and select the item "Enviroment Options".
  2. Click on the "Library" page.
  3. On the field "Library path" add a ";" followed by the unit directory. For instance ";c:\twain".
  4. Click on the ok button.


Component in the web

Installing the component (C++ Builder)

The component also can be installed on Borland C++ Builder. To do so, follow these steps:
  1. First of all, copy (unzip) all the files to any directory. The obj sub-directory is necessary to install the component.
  2. Run a Borland C++ Builder instance
  3. Select the menu File and then the item New.
  4. Item the new dialog, choose the Package item (as shown bellow) and press the OK button.

  5. In the new package item, press the Add button on the Toolbar
  6. Now press the Browse button located in the first tab, Add Unit. As shown bellow:

  7. You will choose now the files to add the package. To do so:
    1. Choose the filter Pascal Unit (*.pas)
    2. Browse for the folder where the Png Delphi files are located
    3. Select the file DelphiTwain.Pas, DelphiTwainUtils.Pas, Twain.Pas
      (multiple select by clicking using the CTRL key pressed)
    4. Press open
  8. Press Ok to close the Add window
  9. Back to C++ Builder window, choose the File menu, and the item Save As...
    Save the file using any name (ex: twainbuilder.dpk), a good idea is to save in the
    same folder as Delphi Twain files.
  10. Press the install button on the Package window to install the component as shown
    bellow

Also, adding the unit to the search path is a good idea

  1. This time, go to the "Tools" menu and select the item "Enviroment Options".
  2. Click on the "Library" page.
  3. On the field "Library path" add a ";" followed by the unit directory. For instance ";c:\twain".
  4. Click on the ok button.


Component in the web

License

The previous versions from this component were unclear about the license to use this component. Here it is:
  1. This component should be distributed freely over the internet only when containing the exact same files from the original packaging.
  2. Modified files may not be distributed. If you want to contribute with Delphi Twain, send the enhancements to the author and if he implements your changes, you will be given the proper credit.
  3. The component may be used in commercial projects but may NEVER be sold as source code.
  4. Commercial graphics libraries are not allowed to use this component WITHOUT AUTHOR PRIOR AGREEMENT.
  5. Credit for the author is required somewhere in the product documentation/or about box/etc for applications distributed over the internet.
  6. Source code may be changed since it's not redistributed.

If are about to use the component in a major project which is going to be distributed over the internet, I'd love to know, so please send me an email telling me about.


Component in the web

Author and website

Gustavo Huffenbacher Daud
Currently, contact me at: gubadaud@terra.com.br

http://delphitwain.sourceforge.net

This is the best place to get the latest version.


Untitled Document

Delphi twain component > About Twain

What is the TWAIN Initiative?
The TWAIN initiative was originally launched in 1992 by leading industry vendors who recognized a need for a standard software protocol and applications programming interface (API) that regulates communication between software applications and imaging devices (the source of the data). TWAIN defines that standard. The three key elements in TWAIN are the application software, the Source Manager software and the Data Source software. The application uses the TWAIN toolkit which is shipped for free.

Why do you need Twain ?
For many years, the computer industry lacked some efficient way to implement support to acquire devices such as scanners, fax-modems. The problem was that every time a new device was released, the applications needed to be update to support it. For this reason, Twain first draft was released in 1992 and later packed with Windows 98. Twain provides a common interface to access such devices. The device takes the responsibility to provide access to the content and Twain interface to properly communicate with the application.

What supports Twain ?
Most of scanners (not to say all), webcams, some fax modems, database engines, digital cameras, and more. With twain, they are all in reach with the application.

About this component
It's not easy implement to implement Twain since it needs to modify the application loop, communicate with the source mananger, with the source and understand the incoming images. For this reason this component was created. Using it doesn't takes more than a few lines of code to get most of Twain features.