View on GitHub

SARAFF SOFTWARE

All products / Saraff.TwainX.Extensions

Image Transfers

XDs exposes the four transfer modes of Saraff.TwainX. Each helper selects and opens the source, sets ICAP_XFERMECH, stores the callbacks for the duration of the transfer and calls TwainX.Acquire().

Method ICAP_XFERMECH Result
NativeTransfer SX_NATIVE EndXferEventArgs.Stream
MemoryTransfer SX_MEMORY MemXferEventArgs.ImageMemXfer chunks
MemFileTransfer SX_MEMFILE MemXferEventArgs.ImageMemXfer chunks in a file format
FileTransfer SX_FILE FileXferEventArgs.ImageFileXfer on disk

Common callback shape

public void NativeTransfer(
    Action<TwainX.EndXferEventArgs> result,
    Action<TwainX.XferDoneEventArgs> imageInfoCallback = null,
    Action completeCallback = null,
    Action<TwainX.AcquireErrorEventArgs> errorCallback = null);

public void MemoryTransfer(
    Action<TwainX.SetupMemXferEventArgs> setupCallback,
    Action<TwainX.MemXferEventArgs> transferCallback,
    Action<TwainX.XferDoneEventArgs> imageInfoCallback = null,
    Action completeCallback = null,
    Action<TwainX.AcquireErrorEventArgs> errorCallback = null);

public void MemFileTransfer(
    Action<TwainX.SetupMemXferEventArgs> setupCallback,
    Action<TwainX.MemXferEventArgs> transferCallback,
    Action<TwainX.XferDoneEventArgs> imageInfoCallback = null,
    Action completeCallback = null,
    Action<TwainX.AcquireErrorEventArgs> errorCallback = null);

public void FileTransfer(
    Action<TwainX.SetupFileXferEventArgs> setupCallback,
    Action<TwainX.FileXferEventArgs> transferCallback,
    Action<TwainX.XferDoneEventArgs> imageInfoCallback = null,
    Action completeCallback = null,
    Action<TwainX.AcquireErrorEventArgs> errorCallback = null);

The two required callbacks of a memory or file transfer are invoked for every page. The optional callbacks are shared by all modes:

Callback Event args When
imageInfoCallback XferDoneEventArgs After each page, before the next setup
completeCallback none When the source reports acquisition complete
errorCallback AcquireErrorEventArgs On an acquisition error

XferDoneEventArgs.GetImageInfo() returns TwainX.ImageInfo with width, height, resolution, bits, planar flag, pixel type and compression. GetExtImageInfo() exposes extended TWAIN information.

Native transfer

using System.IO;

source.NativeTransfer(
    e =>
    {
        using (var stream = e.Stream)
        using (var file = File.Create("scan.png"))
        {
            stream.CopyTo(file);
        }
    },
    imageInfoCallback: e =>
    {
        var info = e.GetImageInfo();
        Console.WriteLine($"{info.ImageWidth}x{info.ImageLength} at {info.XResolution} dpi");
    },
    errorCallback: e => Console.Error.WriteLine(e.Exception));

EndXferEventArgs.Stream is produced by the session for the current page. Copy or save it before the session closes. Setting EndXferEventArgs.Cancel requests cancellation for the current page.

Buffered memory transfer

MemoryTransfer delivers the image in chunks. The setup callback can adjust the buffer size; the transfer callback receives ImageMemXfer data:

source.MemoryTransfer(
    setup =>
    {
        // setup.ImageInfo describes the page; setup.BufferSize can be adjusted.
        Console.WriteLine($"{setup.ImageInfo.ImageWidth}x{setup.ImageInfo.ImageLength}");
    },
    chunk =>
    {
        var data = chunk.ImageMemXfer;
        // The buffer is valid only during this callback.
        // Copy data.ImageData into application-owned storage if it must outlive the callback.
        Console.WriteLine($"chunk {data.Columns}x{data.Rows}, {data.BytesPerRow} bytes/row");
    },
    errorCallback: e => Console.Error.WriteLine(e.Exception));

ImageMemXfer exposes ImageData, BytesPerRow, Columns, Rows, XOffset, YOffset and Compression. The caller is responsible for assembling or decoding the buffer and for copying it out of the callback when the transfer is asynchronous relative to the calling code.

Memory-file transfer

MemFileTransfer uses the same memory callbacks as MemoryTransfer, but the data is produced in the file format selected by ICAP_IMAGEFILEFORMAT:

source.GetCapability<TwFF>(TwCap.ImageFileFormat).Set(TwFF.Png);

var pages = new List<MemoryStream>();
MemoryStream current = null;

source.MemFileTransfer(
    setup => current = new MemoryStream(),
    chunk => current.Write(chunk.ImageMemXfer.ImageData, 0, chunk.ImageMemXfer.ImageData.Length),
    imageInfoCallback: _ =>
    {
        current.Position = 0;
        pages.Add(current);
        current = null;
    },
    completeCallback: () => Console.WriteLine($"{pages.Count} page(s)"),
    errorCallback: e => Console.Error.WriteLine(e.Exception));

// The application owns the per-page streams and must dispose them.
foreach (var page in pages)
{
    page.Dispose();
}

Each stream contains encoded image data for one page. The application owns the streams; copy or dispose them after the transfer completes.

Disk-file transfer

FileTransfer asks the source to write encoded files to disk. The setup callback supplies the file name:

source.GetCapability<TwFF>(TwCap.ImageFileFormat).Set(TwFF.Tiff);

source.FileTransfer(
    setup =>
    {
        setup.FileName = Path.Combine(Path.GetTempPath(), $"scan-{Guid.NewGuid():N}.tif");
    },
    result =>
    {
        var file = result.ImageFileXfer;
        Console.WriteLine($"Written: {file.FileName} ({file.Format})");
    },
    errorCallback: e => Console.Error.WriteLine(e.Exception));

ImageFileXfer exposes FileName and Format.

Source selection and switching

All helpers call XDs.TwainX first, so the source is selected and opened automatically. Only one source is open at a time in a TwainX session. Switching to another XDs closes the current source; switching while the current source is enabled throws InvalidOperationException from the core session.

Concurrency

Only one synchronous transfer may be active per XDsm. A second call throws InvalidOperationException before any callback is stored. The context is cleared when AcquireCompleted or AcquireError is raised, or when XDsm.Dispose() is called.

Synchronous transfer and XDs.AcquireAsync cannot run together on the same XDsm:

Use separate XDsm instances only if the TWAIN DSM can tolerate it; the TWAIN DSM itself is process-wide, so serializing acquisitions is the safe default.

Cancellation

Synchronous transfer cancellation is data-source driven: set EndXferEventArgs.Cancel in the native callback, or use the source UI and its cancel button. XDs.AcquireAsync supports CancellationToken and throws OperationCanceledException; see Asynchronous acquisition.