Search code examples
c#winformsresolutionscanningtwain

Setting resolution for TWAIN scanning


I created an application in WinForms that can list all the twain & wia scanners, and scan with the chosen device from that list.

Whenever i use TWAIN to scan without using the TWAIN user interface, i get images that are bad quality.

My code is based on the wrapper found here: https://www.codeproject.com/Articles/1376/NET-TWAIN-image-scanner?msg=1097187#xx1097187xx and the specifications at http://www.twain.org/wp-content/uploads/2016/03/TWAIN-2.2-Spec.pdf

I tried to set the resolution in dpi, but it doesn't make any difference. The rc always says "failure" after setting the cap:

TwFix32 f32 = new TwFix32();
f32.FromFloat(300);//value of DPI 

// Set X resolution.
TwCapability capX = new TwCapability(TwCap.XResolution, f32.Whole);
rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capX);

// Set Y resolution.
TwCapability capY = new TwCapability(TwCap.YResolution, f32.Whole);
rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capY);

Solution

  • It worked by creating a new constructor:

    public TwCapability(TwCap cap, short sval, TwType twtype)
    {
        Cap = (short)cap;
        ConType = (short)TwOn.One;
        Handle = Twain.GlobalAlloc(0x42, 6);
        IntPtr pv = Twain.GlobalLock(Handle);
        Marshal.WriteInt16(pv, 0, (short)TwType.Int16);
        Marshal.WriteInt32(pv, 2, (int)sval);
        Marshal.WriteInt16(pv, 0, (short)twtype);
        Twain.GlobalUnlock(Handle);
    }
    
    
    TwCapability capResx = new TwCapability(TwCap.ICAP_XRESOLUTION, 300, TwType.Fix32);
    rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capResx);
    
    
    TwCapability capResy = new TwCapability(TwCap.ICAP_YRESOLUTION, 300, TwType.Fix32);
    rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capResy);