0

I have a problem, and i don't know how resolved.. I'm using the drive twain to do scanner some documents, and i don't get create a new BitMap when i'm scanning a big number of the files.. So.. i need help to solution this.. my code is:

public static Bitmap FromHDib(IntPtr dibPtrArg, out ServiceError error)
{
    error = null;

    try
    {

    Win32.BITMAPINFOHEADER bmi;
    IntPtr pixptr;

    var ptr = Win32.GlobalLock(dibPtrArg);

    GetPixelInfo(ptr, out pixptr, out bmi);

    Bitmap bitMap = new Bitmap(bmi.biWidth, bmi.biHeight);

    Graphics scannedImageGraphics = Graphics.FromImage(bitMap);

    **IntPtr hdc = scannedImageGraphics.GetHdc();** //parameter is not valid

    SetDIBitsToDevice(
       hdc,
       0,             // XDest
       0,             // YDest
       bmi.biWidth,
       bmi.biHeight,
       0,             // XSrc
       0,             // YSrc
       0,             // uStartScan
       bmi.biHeight,  // cScanLines
       pixptr,        // lpvBits
       ptr,     // lpbmi
       0);            // 0 = literal RGB values rather than palette

    scannedImageGraphics.ReleaseHdc(hdc);

    const float inchPerMeter = 39.3700787F;
    bitMap.SetResolution(bmi.biXPelsPerMeter / inchPerMeter, bmi.biYPelsPerMeter / inchPerMeter);

    Win32.GlobalUnlock(dibPtrArg);
    Win32.GlobalFree(dibPtrArg);
    Win32.DeleteDC(hdc);

    bitMap.Dispose();

    return bitMap;
    }
    catch (OutOfMemoryException memoryEx)
    {
        return new Bitmap(0, 0);
    }
    catch (ArgumentException argEx)
    {
        return new Bitmap(0, 0);
    }
}
Alex K.
  • 171,639
  • 30
  • 264
  • 288
ipakng
  • 11
  • 1
  • You should clean up in a finally{}. You have a GDI leak of some kind some where. [How to debug GDI Object Leaks?](http://stackoverflow.com/questions/8302287/how-to-debug-gdi-object-leaks) – Alex K. May 18 '16 at 13:00
  • That's very unwise try/catch code. You cannot actually handle those exceptions. If you do anyway then the code will just, eventually, fail a different way. As you found out. **Never** ignore an inconvenient truth, delete those catch statements so you can diagnose the real problem. – Hans Passant May 18 '16 at 13:59
  • the original code don't have try/catch, I put to try to see the error message, because without them simply lock program – ipakng May 18 '16 at 14:04

0 Answers0