Пример #1
1
        private const double Width = 8.27; // in inches.

        #endregion Fields

        #region Methods

        /// <summary>
        /// Aquire an image from the systems default scanner.
        /// </summary>
        /// <returns>byte array of the image.</returns>
        public static byte[] AquireImage()
        {
            var wiaDlg = new CommonDialog();
            var wiaDevice = wiaDlg.ShowSelectDevice(WiaDeviceType.ScannerDeviceType);

            if (wiaDevice.Items.Count == 1)
            {
                var scanner = wiaDevice.Items[1];

                //scanner.Properties["6146"].set_Value(1);
                scanner.Properties["6147"].set_Value(Dpi); // Horizontal resolution.
                scanner.Properties["6148"].set_Value(Dpi); // Vertical resolution.
                scanner.Properties["6151"].set_Value((int)(Dpi * Width)); // Horizontal extent.
                scanner.Properties["6152"].set_Value((int)(Dpi * Height)); // Vertical extent.
                //wiaDevice.Properties[4170].set_Value(1);

                /*var image =
                    wiaDlg.ShowAcquireImage(WiaDeviceType.ScannerDeviceType, WiaImageIntent.ColorIntent,
                        WiaImageBias.MaximizeQuality, FormatID.wiaFormatBMP, true, false, false);*/

                //scanner.Properties.Item
                var image = (ImageFile)wiaDlg.ShowTransfer(scanner, FormatID.wiaFormatJPEG);
                //var image = (ImageFile)scanner.Transfer();
                return (byte[]) image.FileData.get_BinaryData();
            }

            return null;
        }
Пример #2
0
        public ImageFile Scan(ProgressDialogController ctrl, bool colorSetting = true)
        {
            try
            {
                var image  = new ImageFile();
                var dialog = new CommonDialog();

                ctrl.SetTitle("STARTING SCANNER");
                ctrl.SetMessage("This can take a few seconds...");

                var x    = dialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false);
                var item = x.Items[1];
                // HorizontalResolution
                item.Properties["6147"].set_Value(75);
                // VerticalResolution
                item.Properties["6148"].set_Value(75);

                // CurrentInten, 1 - Color, 4 - Black & White
                if (colorSetting)
                {
                    item.Properties["6146"].set_Value(1);
                }
                else
                {
                    item.Properties["6146"].set_Value(4);
                }


                image = dialog.ShowTransfer(item, "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}", true);

                if (image != null)
                {
                    ctrl.SetTitle("SCANNING FINISHED!");
                    ctrl.SetMessage($"File Scanned Successfully...");
                }
                return(image);
            }
            catch (COMException ex)
            {
                if (ex.ErrorCode == -2145320939)
                {
                    throw new ScannerNotFoundException();
                }
                else
                {
                    throw new ScannerException(ex.Message, ex);
                }
            }
        }
Пример #3
0
        private ImageFile Process (CommonDialog commonDialog, Device scannerDevice, int DPI)
        {
            if (scannerDevice != null)
            {
                Item scannerItem = scannerDevice.Items[1];
                if (DPI == 200)
                    AdjustScannerSettings(scannerItem, DPI, 0, 0, 1700, 2338, 0, 0);
                else if (DPI == 300)
                    AdjustScannerSettings(scannerItem, DPI, 0, 0, 2550, 3507, 0, 0);

                object scanResult = commonDialog.ShowTransfer(scannerItem, WIA.FormatID.wiaFormatJPEG, false);
                if (scanResult != null)
                    image = (ImageFile)scanResult;
            }
            return image;
        }
Пример #4
0
        private ImageFile Process(CommonDialog commonDialog, Device scannerDevice, int DPI)
        {
            if (scannerDevice != null)
            {
                Item scannerItem = scannerDevice.Items[1];
                if (DPI == 200)
                {
                    AdjustScannerSettings(scannerItem, DPI, 0, 0, 1700, 2338, 0, 0);
                }
                else if (DPI == 300)
                {
                    AdjustScannerSettings(scannerItem, DPI, 0, 0, 2550, 3507, 0, 0);
                }

                object scanResult = commonDialog.ShowTransfer(scannerItem, WIA.FormatID.wiaFormatJPEG, false);
                if (scanResult != null)
                {
                    image = (ImageFile)scanResult;
                }
            }
            return(image);
        }
Пример #5
0
        /// <summary>
        /// Scan images.
        /// </summary>
        /// <param name="images">Result image file path.</param>
        /// <param name="scannerId">Guid of selected scanner.</param>
        /// <param name="settings"></param>
        public WiaResult Scan(out List <string> images, string scannerId, ScanSettings settings)
        {
            // give a default setting if null
            if (settings == null)
            {
                settings = new ScanSettings();
            }
            images = new List <string>();
            // parse file extension
            string extension;

            switch (settings.ImageFormat)
            {
            default:
            case WiaImageFormat.PNG:
                extension = ".png";
                break;

            case WiaImageFormat.BMP:
                extension = ".bmp";
                break;

            case WiaImageFormat.GIF:
                extension = ".gif";
                break;

            case WiaImageFormat.JPEG:
                extension = ".jpg";
                break;

            case WiaImageFormat.TIFF:
                extension = ".tif";
                break;
            }
            // prepare result
            WiaResult result = new WiaResult();

            result.Error = WiaError.SUCCESS;
            bool hasMorePages = true;

            while (hasMorePages)
            {
                // select the correct scanner using the provided scannerId parameter
                Device device = null;
                foreach (DeviceInfo info in _manager.DeviceInfos)
                {
                    if (info.DeviceID == scannerId)
                    {
                        // connect to scanner
                        device = info.Connect();
                        Property nameProp         = info.Properties["Name"];
                        Property typeProp         = info.Properties["Manufacturer"];
                        Property manufacturerProp = info.Properties["Manufacturer"];
                        Console.WriteLine(nameProp.get_Value().ToString());
                        Console.WriteLine(typeProp.get_Value().ToString());
                        Console.WriteLine(manufacturerProp.get_Value().ToString());
                        break;
                    }
                }
                // device was not found
                if (device == null)
                {
                    // enumerate available devices
                    string availableDevices = "";
                    foreach (DeviceInfo info in _manager.DeviceInfos)
                    {
                        availableDevices += info.DeviceID + "\n";
                    }
                    // show error with available devices
                    string    message = "The device with provided ID could not be found. Available Devices:\n" + availableDevices;
                    WiaResult error   = new WiaResult {
                        Error = WiaError.DEVICE_NOT_FOUND, Message = message
                    };
                    return(error);
                }

                // check paper
                hasMorePages = HasMorePages(device);
                if (!hasMorePages)
                {
                    break;
                }
                // scan
                Item item = device.Items[1];
                try
                {
                    SetScanSettings(item, settings);
                    ImageFile image;
                    if (settings.ShowUI)
                    {
                        // scan image with dialog
                        ICommonDialog wiaCommonDialog = new CommonDialog();
                        image = (ImageFile)wiaCommonDialog.ShowTransfer(item, settings.ImageFormat, false);
                    }
                    else
                    {
                        image = (ImageFile)item.Transfer(settings.ImageFormat);
                    }

                    // create temp directory

                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    // save to temp file
                    string fileName = path + DateTime.Now.ToString("yyyyMMdd-HHmmss", System.Globalization.CultureInfo.InvariantCulture) + extension;
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                    image.SaveFile(fileName);
                    // add file to output list
                    images.Add(fileName);
                }
                catch (COMException ex)
                {
                    result = ShowWiaErrorCode(ex);
                    // if there are successfull scans, we juse break without showing error
                    if (result.Error == WiaError.WIA_ERROR_PAPER_EMPTY && images.Count > 0)
                    {
                        result.Error = WiaError.SUCCESS;
                    }
                    break;
                }
                catch (Exception ex)
                {
                    result.Error   = WiaError.UNKNOWN;
                    result.Message = ex.Message;
                    break;
                }
                finally
                {
                    hasMorePages = HasMorePages(device);
                }
            }
            return(result);
        }
Пример #6
0
        void Scan(ScanColor clr, int dpi, string deviceuuid, string iniPath)
        {
            string deviceid;

            //Choose Scanner
            if (String.IsNullOrEmpty(deviceuuid))
            {
                CommonDialog class1 = new CommonDialog();
                Device       d      = class1.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false);
                if (d == null)
                {
                    return; //no scanner chosen
                }
                deviceid = d.DeviceID;
                if (File.Exists(iniPath))
                {
                    //Connect to Ini File "Config.ini" in current directory
                    IniInterface oIni = new IniInterface(iniPath);
                    oIni.WriteValue("Scan", "deviceuuid", deviceid);
                    CertificateScanner.ExceptionDecor.ExceptionDecorator.Info(String.Format("New scanner with uuid=\"{0}\" added", deviceid));
                }
            }
            else
            {
                deviceid = deviceuuid;
            }
            CommonDialog WiaCommonDialog = new CommonDialog();
            bool         hasMorePages    = true;
            int          x        = 0;
            int          numPages = 0;

            while (hasMorePages)
            {
                //Create DeviceManager
                DeviceManager manager = new DeviceManager();
                Device        WiaDev  = null;
                foreach (DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == deviceid)
                    {
                        Properties infoprop = info.Properties;
                        //connect to scanner
                        WiaDev = info.Connect();
                        break;
                    }
                }
                //Start Scan
                ImageFile img  = null;
                Item      Item = WiaDev.Items[1] as Item;
                //set properties //BIG SNAG!! if you call WiaDev.Items[1] apprently it erases the item from memory so you cant call it again
                Item.Properties["6146"].set_Value((int)clr);//Item MUST be stored in a variable THEN the properties must be set.
                Item.Properties["6147"].set_Value(dpi);
                Item.Properties["6148"].set_Value(dpi);
                try
                {//WATCH OUT THE FORMAT HERE DOES NOT MAKE A DIFFERENCE... .net will load it as a BITMAP!
                    img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}" /*WIA.FormatID.wiaFormatJPEG*/, false);
                    //process image:
                    //Save to file and open as .net IMAGE
                    string varImageFileName = Path.GetTempFileName();
                    if (File.Exists(varImageFileName))
                    {
                        //file exists, delete it
                        File.Delete(varImageFileName);
                    }
                    img.SaveFile(varImageFileName);
                    Image ret;
                    using (var fs = new FileStream(varImageFileName, FileMode.Open)) //File not block
                    {
                        var bmp = new Bitmap(fs);
                        ret = (Bitmap)bmp.Clone();
                        EventHandler <WiaImageEventArgs> temp = Scanning;
                        if (temp != null)
                        {
                            temp(this, new WiaImageEventArgs(ret));
                        }
                    }
                    numPages++;
                    img = null;
                    File.Delete(varImageFileName);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    Item = null;
                    //determine if there are any more pages waiting
                    Property documentHandlingSelect = null;
                    Property documentHandlingStatus = null;

                    foreach (Property prop in WiaDev.Properties)
                    {
                        if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT)
                        {
                            documentHandlingSelect = prop;
                        }
                        if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS)
                        {
                            documentHandlingStatus = prop;
                        }
                    }
                    hasMorePages = false; //assume there are no more pages
                    if (documentHandlingSelect != null)
                    //may not exist on flatbed scanner but required for feeder
                    {
                        //check for document feeder
                        if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0)
                        {
                            hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0);
                        }
                    }
                    x++;
                }
            }
            EventHandler tempCom = ScanComplete;

            if (tempCom != null)
            {
                tempCom(this, EventArgs.Empty);
            }
        }
Пример #7
0
        private static List <Bitmap> AcquireBrother(Device device, ScanSettings settings)
        {
            List <Bitmap> images       = new List <Bitmap>();
            bool          hasMorePages = true;
            Item          scan         = null;

            SetDeviceHandling(ref device, settings);
            SetDeviceProperties(ref device, settings);

            try
            {   //Connect to scanner
                scan = device.Items[1] as Item;
            }
            catch (Exception)
            {
                throw new Exception("Cannot connect to scanner, please check your device and try again.");
            }

            //Acquisition iteration
            ICommonDialog wiaCommonDialog = new CommonDialog();

            while (hasMorePages)
            {
                Logger.Log("DEBUG: document handling " + GetDeviceIntProperty(ref device, WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT));
                Logger.Log("DEBUG: feeder status " + GetDeviceIntProperty(ref device, WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS));

                try
                {
                    //Some scanner need WIA_DPS_PAGES to be set to 1, otherwise all pages are acquired but only one is returned as ImageFile
                    SetDeviceIntProperty(ref device, WIA_PROPERTIES.WIA_DPS_PAGES, 1);

                    //Scan image
                    ImageFile image = (ImageFile)wiaCommonDialog.ShowTransfer(scan, wiaFormatBMP, false);

                    if (image != null)
                    {
                        // convert to byte array
                        Byte[] imageBytes = (byte[])image.FileData.get_BinaryData();

                        // add file to output list
                        Bitmap bmp = new Bitmap(Image.FromStream(new MemoryStream(imageBytes)));
                        images.Add(bmp);

                        //Cleanup
                        image      = null;
                        imageBytes = null;
                    }
                    else
                    {
                        Logger.Log("Scan cancelled");
                        break;
                    }

                    // assume there are no more pages
                    hasMorePages = false;
                    if (settings.adf)
                    {
                        try
                        {   //try to read feed ready property (some scanners report ready even if no more pages)
                            int status = GetDeviceIntProperty(ref device, WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS);
                            hasMorePages = (status & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0;
                        }
                        catch { }
                    }
                }
                catch (System.Runtime.InteropServices.COMException ex)
                {
                    switch ((uint)ex.ErrorCode)
                    {
                    case WIA_ERRORS.WIA_ERROR_PAPER_EMPTY:
                        Logger.Log("Paper feed empty");
                        hasMorePages = false;
                        break;

                    case WIA_ERRORS.WIA_ERROR_PAPER_JAM:
                        Program.ShowError("Paper jam inside the scanner feeder");
                        break;

                    case WIA_ERRORS.WIA_ERROR_BUSY:
                        Logger.Log("Device is busy, retrying in 2s...");
                        System.Threading.Thread.Sleep(2000);
                        break;

                    default:
                        break;
                    }
                }
            }

            device = null;
            return(images);
        }
Пример #8
0
        void Scan(ScanColor clr, int dpi)
        {
            string deviceid;
            //Choose Scanner
            CommonDialog class1 = new CommonDialog();
            Device       d      = class1.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false);

            if (d != null)
            {
                deviceid = d.DeviceID;
            }
            else
            {
                //no scanner chosen
                return;
            }
            WIA.CommonDialog WiaCommonDialog = new CommonDialog();
            bool             hasMorePages    = true;
            int x        = 0;
            int numPages = 0;

            while (hasMorePages)
            {
                //Create DeviceManager
                DeviceManager manager = new DeviceManager();
                Device        WiaDev  = null;
                foreach (DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == deviceid)
                    {
                        WIA.Properties infoprop = null;
                        infoprop = info.Properties;
                        //connect to scanner
                        WiaDev = info.Connect();
                        break;
                    }
                }
                //Start Scan
                WIA.ImageFile img  = null;
                WIA.Item      Item = WiaDev.Items[1] as WIA.Item;
                //set properties //BIG SNAG!! if you call WiaDev.Items[1] apprently it erases the item from memory so you cant call it again
                Item.Properties["6146"].set_Value((int)clr);//Item MUST be stored in a variable THEN the properties must be set.
                Item.Properties["6147"].set_Value(dpi);
                Item.Properties["6148"].set_Value(dpi);
                try
                {//WATCH OUT THE FORMAT HERE DOES NOT MAKE A DIFFERENCE... .net will load it as a BITMAP!
                    var testFormat = FormatID.wiaFormatJPEG;
                    img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, testFormat, false);
                    //process image:
                    //Save to file and open as .net IMAGE
                    string varImageFileName = Path.GetTempFileName();
                    if (File.Exists(varImageFileName))
                    {
                        //file exists, delete it
                        File.Delete(varImageFileName);
                    }
                    img.SaveFile(varImageFileName);
                    Image ret = Image.FromFile(varImageFileName);
                    EventHandler <WiaImageEventArgs> temp = Scanning;
                    if (temp != null)
                    {
                        temp(this, new WiaImageEventArgs(ret));
                    }
                    numPages++;
                    img = null;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    Item = null;
                    //determine if there are any more pages waiting
                    Property documentHandlingSelect = null;
                    Property documentHandlingStatus = null;

                    foreach (Property prop in WiaDev.Properties)
                    {
                        if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT)
                        {
                            documentHandlingSelect = prop;
                        }
                        if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS)
                        {
                            documentHandlingStatus = prop;
                        }
                    }
                    hasMorePages = false; //assume there are no more pages
                    if (documentHandlingSelect != null)
                    //may not exist on flatbed scanner but required for feeder
                    {
                        //check for document feeder
                        if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0)
                        {
                            hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0);
                        }
                    }
                    x++;
                }
            }
            EventHandler tempCom = ScanComplete;

            if (tempCom != null)
            {
                tempCom(this, EventArgs.Empty);
            }
        }
Пример #9
0
        private static List <Image> AcquireNormal(Device device, ScanSettings settings)
        {
            DeviceManager manager      = new DeviceManager();
            List <Image>  images       = new List <Image>();
            bool          hasMorePages = true;
            Item          scan         = null;

            //Acquisition iteration
            ICommonDialog wiaCommonDialog = new CommonDialog();

            while (hasMorePages)
            {
                try
                {   //Looks like these need to be done for each iteration
                    SetDeviceHandling(ref device, settings);
                    scan = device.Items[1] as Item;
                    SetDeviceProperties(ref device, settings);
                }
                catch (Exception)
                {
                    throw new Exception("Cannot connect to scanner, please check your device and try again.");
                }

                Logger.Log("DEBUG: document handling " + GetDeviceIntProperty(ref device, WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT));
                Logger.Log("DEBUG: feeder status " + GetDeviceIntProperty(ref device, WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS));

                try
                {
                    //Scan image
                    ImageFile image = (ImageFile)wiaCommonDialog.ShowTransfer(scan, wiaFormatBMP, false);

                    if (image != null)
                    {
                        // convert to byte array
                        Byte[] imageBytes = (byte[])image.FileData.get_BinaryData();

                        // add file to output list
                        images.Add(Image.FromStream(new MemoryStream(imageBytes)));

                        //Cleanup
                        image      = null;
                        imageBytes = null;
                    }
                    else
                    {
                        Logger.Log("Scan cancelled");
                        break;
                    }

                    // assume there are no more pages
                    hasMorePages = false;
                    if (settings.adf)
                    {
                        try
                        {   //try to read feed ready property (some scanners report ready even if no more pages)
                            int status = GetDeviceIntProperty(ref device, WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS);
                            hasMorePages = (status & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0;

                            Logger.Log("ADF has more pages: " + (hasMorePages ? "Yes" : "No"));
                        }
                        catch { }
                    }
                }
                catch (System.Runtime.InteropServices.COMException ex)
                {
                    switch ((uint)ex.ErrorCode)
                    {
                    case WIA_ERRORS.WIA_ERROR_PAPER_EMPTY:
                        Logger.Log("Paper feed empty");
                        if (images.Count == 0 && settings.adf && settings.tryFlatbed)
                        {       //if no page scanned try try flatbed
                            settings.adf = false;
                        }
                        else
                        {
                            hasMorePages = false;
                        }
                        break;

                    case WIA_ERRORS.WIA_ERROR_PAPER_JAM:
                        Program.ShowError("Paper jam inside the scanner feeder");
                        break;

                    case WIA_ERRORS.WIA_ERROR_BUSY:
                        Logger.Log("Device is busy, retrying in 2s...");
                        System.Threading.Thread.Sleep(2000);
                        break;

                    default:
                        throw ex;
                    }
                }
            }

            device = null;
            return(images);
        }
Пример #10
0
        private XImage ScanOne()
        {
            XImage ximage = null;

            try
            {
                // find our device (scanner previously selected with commonDialog.ShowSelectDevice)
                DeviceManager manager    = new DeviceManager();
                DeviceInfo    deviceInfo = null;
                foreach (DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == _deviceId)
                    {
                        deviceInfo = info;
                    }
                }

                if (deviceInfo != null)
                {
                    Device       device       = deviceInfo.Connect();
                    CommonDialog commonDialog = new CommonDialog();

                    Item item = device.Items[1];
                    int  dpi  = 150;

                    // configure item
                    SetItemIntProperty(ref item, 6147, dpi);                  // 150 dpi
                    SetItemIntProperty(ref item, 6148, dpi);                  // 150 dpi
                    SetItemIntProperty(ref item, 6151, (int)(dpi * _width));  // scan width
                    SetItemIntProperty(ref item, 6152, (int)(dpi * _height)); // scan height

                    try
                    {
                        SetItemIntProperty(ref item, 6146, 2); // greyscale
                    }
                    catch
                    {
                        Debug.WriteLine("Failed to set greyscale");
                    }

                    try
                    {
                        SetItemIntProperty(ref item, 4104, 8); // bit depth
                    }
                    catch
                    {
                        Debug.WriteLine("Failed to set bit depth");
                    }

                    int deviceHandling = _adf ? 1 : 2; // 1 for ADF, 2 for flatbed

                    // configure device
                    SetDeviceIntProperty(ref device, 3088, deviceHandling);
                    int handlingStatus = GetDeviceIntProperty(ref device, 3087);

                    if (handlingStatus == deviceHandling)
                    {
                        ImageFile image = commonDialog.ShowTransfer(item, formatJpeg, true);

                        // save image to a temp file and then load into an XImage
                        string tempPath = System.IO.Path.GetTempFileName();
                        File.Delete(tempPath);
                        tempPath = System.IO.Path.ChangeExtension(tempPath, "jpg");
                        image.SaveFile(tempPath);
                        ximage = XImage.FromFile(tempPath);

                        this.PageImages.Add(tempPath);
                        _tempFilesToDelete.Add(tempPath);
                    }
                }
            }
            catch (COMException ex)
            {
                ximage = null;

                // paper empty
                if ((uint)ex.ErrorCode != 0x80210003)
                {
                    throw;
                }
            }

            return(ximage);
        }
Пример #11
0
        private static List<Image> AcquireNormal(Device device, ScanSettings settings)
        {
            DeviceManager manager = new DeviceManager();
            List<Image> images = new List<Image>();
            bool hasMorePages = true;
            Item scan = null;

            //Acquisition iteration
            ICommonDialog wiaCommonDialog = new CommonDialog();
            while (hasMorePages)
            {
                try
                {   //Looks like these need to be done for each iteration
                    SetDeviceHandling(ref device, settings);
                    scan = device.Items[1] as Item;
                    SetDeviceProperties(ref device, settings);
                }
                catch (Exception)
                {
                    throw new Exception("Cannot connect to scanner, please check your device and try again.");
                }

                Logger.Log("DEBUG: document handling " + GetDeviceIntProperty(ref device, WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT));
                Logger.Log("DEBUG: feeder status " + GetDeviceIntProperty(ref device, WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS));

                try
                {
                    //Scan image
                    ImageFile image = (ImageFile)wiaCommonDialog.ShowTransfer(scan, wiaFormatBMP, false);

                    if (image != null)
                    {
                        // convert to byte array
                        Byte[] imageBytes = (byte[])image.FileData.get_BinaryData();

                        // add file to output list
                        images.Add(Image.FromStream(new MemoryStream(imageBytes)));

                        //Cleanup
                        image = null;
                        imageBytes = null;
                    }
                    else
                    {
                        Logger.Log("Scan cancelled");
                        break;
                    }

                    // assume there are no more pages
                    hasMorePages = false;
                    if (settings.adf)
                    {
                        try
                        {   //try to read feed ready property (some scanners report ready even if no more pages)
                            int status = GetDeviceIntProperty(ref device, WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS);
                            hasMorePages = (status & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0;

                            Logger.Log("ADF has more pages: " + (hasMorePages ? "Yes" : "No"));
                        }
                        catch { }
                    }
                }
                catch (System.Runtime.InteropServices.COMException ex)
                {
                    switch ((uint)ex.ErrorCode)
                    {
                        case WIA_ERRORS.WIA_ERROR_PAPER_EMPTY:
                            Logger.Log("Paper feed empty");
                            if (images.Count == 0 && settings.adf && settings.tryFlatbed)
                            {   //if no page scanned try try flatbed
                                settings.adf = false;
                            }
                            else
                                hasMorePages = false;
                            break;

                        case WIA_ERRORS.WIA_ERROR_PAPER_JAM:
                            Program.ShowError("Paper jam inside the scanner feeder");
                            break;

                        case WIA_ERRORS.WIA_ERROR_BUSY:
                            Logger.Log("Device is busy, retrying in 2s...");
                            System.Threading.Thread.Sleep(2000);
                            break;

                        default:
                            throw ex;
                    }
                }
            }

            device = null;
            return images;
        }