Exemplo n.º 1
0
        private WIA.Item GetScanningProperties(bool showUI, CommonDialogClass wiaCommonDialog, Device WiaDev)
        {
            WIA.Items items = null;
            if (showUI)
            {
                try
                {
                    items = wiaCommonDialog.ShowSelectItems(WiaDev, WiaImageIntent.TextIntent, WiaImageBias.MinimizeSize, false, true, false);
                }
                catch (Exception)
                {
                }
            }
            else
            {
                items = WiaDev.Items;
            }

            WIA.Item scanningItem = null;
            if (items != null && items.Count > 0)
            {
                scanningItem = items[1] as WIA.Item;
            }
            return(scanningItem);
        }
Exemplo n.º 2
0
        private void SetupPageSize(WIA.Item item, PageSize pageSize, ColorDepth colorDepth, Resolution resolution, Orientation orientation, bool setSize)
        {
            if (item == null)
            {
                return;
            }

            item.Properties["Horizontal Resolution"].set_Value(resolution.Value);
            item.Properties["Vertical Resolution"].set_Value(resolution.Value);
            item.Properties["Current Intent"].set_Value(colorDepth.Value);
            item.Properties["Bits Per Pixel"].set_Value(colorDepth.BitsPerPixel);

            double hExtent = item.Properties["Horizontal Extent"].SubTypeMax;
            double vExtent = item.Properties["Vertical Extent"].SubTypeMax;

            if (setSize)
            {
                if (orientation.Direction == 0)
                {
                    item.Properties["Horizontal Extent"].set_Value(resolution.Value * pageSize.Width);
                    item.Properties["Vertical Extent"].set_Value(resolution.Value * pageSize.Height);
                }
                else
                {
                    item.Properties["Horizontal Extent"].set_Value(resolution.Value * pageSize.Height);
                    item.Properties["Vertical Extent"].set_Value(resolution.Value * pageSize.Width);
                }
            }
            else
            {
                item.Properties["Horizontal Extent"].set_Value(hExtent);
                item.Properties["Vertical Extent"].set_Value(vExtent);
            }
        }
Exemplo n.º 3
0
        public override void AcquireImages(bool showUI)
        {
            CommonDialogClass wiaCommonDialog = new CommonDialogClass();

            if (m_DeviceID == null)
            {
                SelectDevice();
            }

            //Create DeviceManager
            Device WiaDev = CreateDeviceManager();

            WIA.Item scanningItem = GetScanningProperties(showUI, wiaCommonDialog, WiaDev);
            if (scanningItem == null)
            {
                return;
            }

            WIA.ImageFile imgFile = null;
            WIA.Item      item    = null;

            PrepareImagesList();

            //Start Scan
            while (HasMorePages(WiaDev))
            {
                item = scanningItem;

                try
                {
                    imgFile = ScanImage(wiaCommonDialog, imgFile, item);
                }
                catch (COMException ex)
                {
                    if ((WiaScannerError)ex.ErrorCode == WiaScannerError.PaperEmpty)
                    {
                        break;
                    }
                    else
                    {
                        WiaScannerException se = BuildScannerException(WiaDev, ex);
                        throw se;
                    }
                }
                catch (Exception ex)
                {
                    WiaScannerException se = BuildScannerException(WiaDev, ex);
                    throw se;
                }
                finally
                {
                    item = null;
                }
            }
        }
Exemplo n.º 4
0
        public WIA.ImageFile ScanAndSaveOnePage()
        {
            WIA.CommonDialog  Dialog1        = new WIA.CommonDialogClass();
            WIA.DeviceManager DeviceManager1 = new WIA.DeviceManagerClass();
            System.Object     Object1        = null;
            System.Object     Object2        = null;
            WIA.Device        Scanner        = null;

            try
            {
                Scanner = Dialog1.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, false, false);
            }
            catch
            {
                MessageBox.Show("请确认是否联系设备");
                return(null);

                throw;
            }
            WIA.Item Item1 = Scanner.Items[1];
            setItem(Item1, "4104", 24);
            setItem(Item1, "6146", 2);
            setItem(Item1, "6147", 150);
            setItem(Item1, "6148", 150);
            setItem(Item1, "6151", 150 * 8.5);
            setItem(Item1, "6152", 150 * 11);

            WIA.ImageFile    Image1        = new WIA.ImageFile();
            WIA.ImageProcess ImageProcess1 = new WIA.ImageProcess();
            Object1 = (Object)"Convert";
            ImageProcess1.Filters.Add(ImageProcess1.FilterInfos.get_Item(ref Object1).FilterID, 0);

            Object1 = (Object)"FormatID";
            Object2 = (Object)WIA.FormatID.wiaFormatBMP;
            ImageProcess1.Filters[1].Properties.get_Item(ref Object1).set_Value(ref Object2);

            Object1 = null;
            Object2 = null;

            Image1 = (WIA.ImageFile)Item1.Transfer(WIA.FormatID.wiaFormatBMP);

            return(Image1);

            //string DestImagePath = @"C:\test.bmp";
            //File.Delete(DestImagePath);
            //Image1.SaveFile(DestImagePath);
        }
Exemplo n.º 5
0
        ImageFile Scan(String str)
        {
            LogContent("process", "Scanning");
            CommonDialog dialog       = new WIA.CommonDialog();
            ImageFile    scannedImage = null;

            if (Set.default_device == null)
            {
                WiaDev = dialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);
                MessageBoxResult result = MessageBox.Show("Ustawić urządzenie jako domyślne?", "Potwierdzenie", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    Set.default_device = WiaDev;
                }
            }
            else
            {
                WiaDev = Set.default_device;
            }

            //Start Scan

            WIA.Item Item = WiaDev.Items[1] as WIA.Item;

            try
            {
                scannedImage = (ImageFile)dialog.ShowTransfer(Item, EnvFormatID.wiaFormatPNG, false);
                String path = Set.path;
                destination = path + str + "_" + Note.Text + ".png";
                LogContent("destination", destination);
                scannedImage.SaveFile(destination);
                return(scannedImage);
            }
            catch (Exception e)
            {
                MessageBox.Show("Error " + e.Message);
            }
            finally
            {
            }
            return(null);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Scan a single image
        /// </summary>
        public byte[] ScanSingle(ScannerInfo source)
        {
            WIA.Device wiaDevice = source.GetDevice();
            // Manager
            WIA.DeviceManager wiaManager = new WIA.DeviceManager();

            try
            {
                // Get items
                WIA.Item wiaItem = wiaDevice.Items[1];
                int      inColor = 2, dpi = 300;
                wiaItem.Properties["6146"].set_Value((int)inColor);//Item MUST be stored in a variable THEN the properties must be set.
                wiaItem.Properties["6147"].set_Value(dpi);
                wiaItem.Properties["6148"].set_Value(dpi);

                var imageFile = (ImageFile)(new CommonDialog()).ShowTransfer(wiaItem, "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}", false); //wiaItem.Transfer("{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}") as WIA.ImageFile;

                return(imageFile.FileData.get_BinaryData());
            }
            catch (Exception e)
            {
                throw;
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerName"></param>
        /// <returns>Scanned images.</returns>
        public static List <string> Scan(ScanSettings settings)
        {
            List <string> images       = new List <string>();
            bool          hasMorePages = true;

            while (hasMorePages)
            {
                // select the correct scanner using the provided scannerId parameter
                WIA.DeviceManager manager = new WIA.DeviceManager();
                WIA.Device        device  = null;
                foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == settings.DeviceId)
                    {
                        // connect to scanner
                        device = info.Connect();
                        break;
                    }
                }
                // device was not found
                if (device == null)
                {
                    // enumerate available devices
                    string availableDevices = "";
                    foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                    {
                        availableDevices += info.DeviceID + "\n";
                    }

                    // show error with available devices
                    throw new Exception("The device with provided ID could not be found. Available Devices:\n" + availableDevices);
                }
                WIA.Item item = device.Items[1] as WIA.Item;
                try
                {
                    // scan image
                    WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
                    WIAScanner.AdjustScannerSettings(item, settings.WIA_Intent);
                    WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);

                    var imageBytes = (byte[])image.FileData.get_BinaryData();
                    images.Add(Convert.ToBase64String(imageBytes));
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                finally
                {
                    item = null;
                    //determine if there are any more pages waiting
                    WIA.Property documentHandlingSelect = null;
                    WIA.Property documentHandlingStatus = null;
                    foreach (WIA.Property prop in device.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;
                        }
                    }
                    // assume there are no more pages
                    hasMorePages = false;
                    // may not exist on flatbed scanner but required for feeder
                    if (documentHandlingSelect != null)
                    {
                        // 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);
                        }
                    }
                }
            }
            return(images);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Start scan
        /// </summary>
        public void ScanAsync(ScannerInfo source)
        {
            if (source == null)
            {
                return;
            }

            WIA.Device wiaDevice = source.GetDevice();
            // Manager
            WIA.DeviceManager wiaManager = new WIA.DeviceManager();

            bool hasMorePages = true;

            while (hasMorePages)
            {
                try
                {
                    // Get items
                    WIA.Item wiaItem = wiaDevice.Items[1];
                    int      inColor = 2, dpi = 300;
                    wiaItem.Properties["6146"].set_Value((int)inColor);    //Item MUST be stored in a variable THEN the properties must be set.
                    wiaItem.Properties["6147"].set_Value(dpi);
                    wiaItem.Properties["6148"].set_Value(dpi);

//                        var imageFile = (ImageFile)(new CommonDialog()).ShowTransfer(wiaItem, "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}", false); //wiaItem.Transfer("{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}") as WIA.ImageFile;

                    var imageFile = wiaItem.Transfer("{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}") as WIA.ImageFile;

                    if (this.ScanCompleted != null)
                    {
                        this.ScanCompleted(this, new ScanCompletedEventArgs(imageFile.FileData.get_BinaryData()));
                    }
                }
                catch (Exception)
                {
                    break;
                }
                finally
                {
                    //determine if there are any more pages waiting
                    WIA.Property documentHandlingSelect = null;
                    WIA.Property documentHandlingStatus = null;

                    foreach (WIA.Property prop in wiaDevice.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);
                        }
                    }

                    if (hasMorePages && this.SingleOnly)
                    {
                        hasMorePages = false;
                    }
                }
            }
        }
Exemplo n.º 9
0
        public static List <Bitmap> Scan(string scannername)
        {
            List <Bitmap> images = new List <Bitmap>();

            bool hasMorePages = true;

            while (hasMorePages)
            {
                WIA.DeviceManager manager = new WIA.DeviceManager();
                WIA.Device        device  = null;
                foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.Properties["Name"].get_Value().ToString() == scannername)
                    {
                        device = info.Connect();
                        break;
                    }
                }

                if (device == null)
                {
                    string availableDevices = "";
                    foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                    {
                        availableDevices += info.Properties["Name"].get_Value().ToString() + "\n";
                    }


                    throw new Exception("Указанное устройство не найдено. Доступные устройства: " + availableDevices);
                }

                WIA.Item item = device.Items[1] as WIA.Item;
                try
                {
                    WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
                    AdjustScannerSettings(item, 100, 0, 0, 850, 1170, 0, 0, true);
                    WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);

                    //темповый файл
                    string fileName = Path.GetTempFileName();
                    File.Delete(fileName);
                    image.SaveFile(fileName);
                    image = null;
                    images.Add(new Bitmap(fileName));
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                finally
                {
                    item = null;


                    WIA.Property documentHandlingSelect = null;
                    WIA.Property documentHandlingStatus = null;

                    foreach (WIA.Property prop in device.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;


                    if (documentHandlingSelect != null)
                    {
                        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);
                        }
                    }
                }
            }

            return(images);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerName"></param>
        /// <returns>Scanned images.</returns>
        public List <Image> Scan(string scannerId, int pages)
        {
            //List<Image> images = new List<Image>();
            bool hasMorePages = true;
            int  numbrPages   = pages;

            // select the correct scanner using the provided scannerId parameter
            WIA.DeviceManager manager = new WIA.DeviceManager();
            WIA.Device        device  = null;

            foreach (WIA.DeviceInfo info in manager.DeviceInfos)
            {
                if (info.DeviceID == scannerId)
                {
                    // connect to scanner
                    device = info.Connect();
                    break;
                }
            }
            // device was not found
            if (device == null)
            {
                // enumerate available devices
                string availableDevices = "";
                foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                {
                    availableDevices += info.DeviceID + "\n";
                }

                // show error with available devices
                throw new Exception("The device with provided ID could not be found. Available Devices:\n" + availableDevices);
            }

            SetWIAProperty(device.Properties, WIA_DEVICE_PROPERTY_PAGES_ID, 1);

            item = device.Items[1] as WIA.Item;
            int    dpi          = 300;
            int    inch         = 254;
            double dpiMM        = dpi / inch;
            double widthFormat  = 210;
            double heightFormat = 297;
            int    widthPixel   = (int)(widthFormat * dpiMM);
            int    heightPixel  = (int)(heightFormat * dpiMM);

            AdjustScannerSettings(item, dpi, 0, 0, widthPixel, heightPixel, 0, 0, 2);

            while (hasMorePages)
            {
                Thread thread = new Thread(goScan);
                thread.Start();
                thread.Join();

                /*
                 * finally
                 * {
                 *  //item = null;
                 *  //determine if there are any more pages waiting
                 *  WIA.Property documentHandlingSelect = null;
                 *  WIA.Property documentHandlingStatus = null;
                 *  foreach (WIA.Property prop in device.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;
                 *  }
                 *  // assume there are no more pages
                 *  hasMorePages = false;
                 *  // may not exist on flatbed scanner but required for feeder
                 *  if (documentHandlingSelect != null)
                 *  {
                 *      // 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);
                 *      }
                 *  }
                 * }
                 */
                numbrPages -= 1;
                if (numbrPages > 0)
                {
                    hasMorePages = true;
                }
                else
                {
                    hasMorePages = false;
                }
            }
            return(images);
        }
Exemplo n.º 11
0
        private WIA.ImageFile ScanImage(CommonDialogClass wiaCommonDialog, WIA.ImageFile imgFile, WIA.Item item)
        {
            imgFile = (ImageFile)wiaCommonDialog.ShowTransfer(item, ImageFormat.Tiff.Guid.ToString("B") /* wiaFormatTiff*/, false);

            byte[]       buffer = (byte[])imgFile.FileData.get_BinaryData();
            MemoryStream ms     = new MemoryStream(buffer);

            m_ImagesList.Add(Image.FromStream(ms));

            imgFile = null;
            return(imgFile);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerName"></param>
        /// <returns>Scanned images.</returns>
        public static List <Image> Scan(string scannerId)
        {
            List <Image> images       = new List <Image>();
            bool         hasMorePages = true;

            while (hasMorePages)
            {
                // select the correct scanner using the provided scannerId parameter
                WIA.DeviceManager manager = new WIA.DeviceManager();
                WIA.Device        device  = null;
                foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == scannerId)
                    {
                        // connect to scanner
                        device = info.Connect();
                        break;
                    }
                }
                // device was not found
                if (device == null)
                {
                    // enumerate available devices
                    string availableDevices = "";
                    foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                    {
                        availableDevices += info.DeviceID + "\n";
                    }

                    // show error with available devices
                    throw new Exception("The device with provided ID could not be found. Available Devices:\n" + availableDevices);
                }
                WIA.Item item = device.Items[1] as WIA.Item;
                //AdjustScannerSettings(scannnerItem, (int)nudRes.Value, 0, 0, (int)nudWidth.Value, (int)nudHeight.Value, 0, 0, cmbCMIndex);
                AdjustScannerSettings(item, 2);
                try
                {
                    // scan image
                    WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
                    WIA.ImageFile     image           = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);

                    // save to temp file
                    string fileName = Path.GetTempFileName();
                    File.Delete(fileName);
                    image.SaveFile(fileName);
                    image = null;
                    // add file to output list
                    images.Add(Image.FromFile(fileName));
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                finally
                {
                    item = null;
                    //determine if there are any more pages waiting
                    WIA.Property documentHandlingSelect = null;
                    WIA.Property documentHandlingStatus = null;
                    foreach (WIA.Property prop in device.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;
                        }
                    }
                    // assume there are no more pages
                    hasMorePages = false;
                    // may not exist on flatbed scanner but required for feeder
                    if (documentHandlingSelect != null)
                    {
                        // 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);
                        }
                    }
                }
            }
            return(images);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Setup Page Size
        /// </summary>
        /// <param name="wia"></param>
        private void SetupPageSize(Device wia, bool rotatePage, PageSize pageSize, int DPI, WIA.Item item)
        {
            try
            {
                foreach (WIA.Property itemProperty in item.Properties)
                {
                    if (itemProperty.Name.Equals("Horizontal Resolution"))
                    {
                        ((IProperty)itemProperty).set_Value(DPI);
                    }
                    else if (itemProperty.Name.Equals("Vertical Resolution"))
                    {
                        ((IProperty)itemProperty).set_Value(DPI);
                    }
                    else if (itemProperty.Name.Equals("Horizontal Extent"))
                    {
                        double extent = DPI * pageSize.Height;

                        if (rotatePage)
                        {
                            extent = DPI * pageSize.Width;
                        }


                        ((IProperty)itemProperty).set_Value(extent);
                    }
                    else if (itemProperty.Name.Equals("Vertical Extent"))
                    {
                        double extent = DPI * pageSize.Width;

                        if (rotatePage)
                        {
                            extent = pageSize.Height * DPI;
                        }


                        ((IProperty)itemProperty).set_Value(extent);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            //Setup Page Size Property
        }
        public static Image ScanFile(string folderName, string fileName, ImageFormat imageFormat, bool overrideIfExists,
                                     ref string savedPath, ref string errorMessage)
        {
            WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
            Device            device          = ConnectToScanner(GetScannerDevice());

            if (device == null)
            {
                return(null);
            }

            Image scannedImage = null;

            try
            {
                WIA.ImageFile image = null;
                WIA.Item      item  = device.Items[1] as WIA.Item;
                switch (imageFormat)
                {
                case ImageFormat.JPEG:
                    image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, JPEGFormat);
                    break;

                case ImageFormat.PNG:
                    image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, PNGFormat);
                    break;
                }

                if (image != null)
                {
                    string path     = FileManager.GetServerDirectoryPath(DB_ServerDirectory.ScanDirectory);
                    string fullPath = "";

                    string serverDirectorBaseFile =
                        FileManager.GetServerDirectoryName(DB_ServerDirectory.ScanDirectory);
                    if (!Directory.Exists(Path.Combine(path, serverDirectorBaseFile)))
                    {
                        Directory.CreateDirectory(Path.Combine(path, serverDirectorBaseFile));
                    }
                    if (!Directory.Exists(Path.Combine(Path.Combine(path, serverDirectorBaseFile), folderName)))
                    {
                        Directory.CreateDirectory(Path.Combine(Path.Combine(path, serverDirectorBaseFile), folderName));
                    }

                    switch (imageFormat)
                    {
                    case ImageFormat.JPEG:
                        fullPath = Path.Combine(Path.Combine(Path.Combine(path, serverDirectorBaseFile), folderName), fileName + ".jpg");
                        break;

                    case ImageFormat.PNG:
                        fullPath = Path.Combine(Path.Combine(Path.Combine(path, serverDirectorBaseFile), folderName), fileName + ".png");
                        break;
                    }

                    if (File.Exists(Path.GetFullPath(fullPath)))
                    {
                        if (overrideIfExists)
                        {
                            File.Delete(Path.GetFullPath(fullPath));
                        }
                        else
                        {
                            errorMessage = "File is already exists";
                            return(null);
                        }
                    }

                    try
                    {
                        image.SaveFile(Path.GetFullPath(fullPath));
                    }
                    catch (Exception e)
                    {
                        errorMessage = "Network error";
                        return(null);
                    }

                    savedPath    = Path.GetFullPath(fullPath);
                    scannedImage = Image.FromFile(Path.GetFullPath(fullPath));
                }
            }
            catch (COMException e)
            {
                // Convert the error code to UINT
                uint errorCode = (uint)e.ErrorCode;

                // See the error codes
                if (errorCode == 0x80210006)
                {
                    errorMessage = "The scanner is busy or isn't ready";
                }
                else if (errorCode == 0x80210064)
                {
                    errorMessage = "The scanning process has been canceled.";
                }
                else if (errorCode == 0x8021000C)
                {
                    errorMessage = "There is an incorrect setting on the WIA device.";
                }
                else if (errorCode == 0x80210005)
                {
                    errorMessage = "The device is offline. Make sure the device is powered on and connected to the PC.";
                }
                else if (errorCode == 0x80210001)
                {
                    errorMessage = "An unknown error has occurred with the WIA device.";
                }
            }

            return(scannedImage);
        }
        protected void btnEscanear_Click(object sender, EventArgs e)
        {
            WIA.CommonDialog  Dialog1        = new WIA.CommonDialog();
            WIA.DeviceManager DeviceManager1 = new WIA.DeviceManager();
            WIA.Device        Scanner        = null;

            Scanner = Dialog1.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, false, true);
            WIA.Item      Item1  = Scanner.Items[1];
            WIA.ImageFile Imagen = new WIA.ImageFile();
            Imagen = (WIA.ImageFile)Item1.Transfer("{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}");
            string DestImagePath = @"~\imagenes\temporal\Scan.png";

            File.Delete(DestImagePath);
            Imagen.SaveFile(DestImagePath);
            Image1.ImageUrl = @"~\imagenes\temporal\Scan.png";

            string nombreArchivo = "Scan.png";



            selectedTipo = dropTipoDocumento.SelectedValue.ToString();


            ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0);
            Bitmap image1 = new Bitmap(Server.MapPath(@"imagenes").ToString() + @"\" + nombreArchivo);
            Bitmap image2 = null;

            if (dropTipoDocumento.SelectedValue == "acta")
            {
                image2 = new Bitmap(Server.MapPath(@"imagenes").ToString() + @"\templer.jpg");
            }
            else if (dropTipoDocumento.SelectedValue == "curp")
            {
                image2 = new Bitmap(Server.MapPath(@"imagenes").ToString() + @"\curptemp.jpg");
            }
            else
            {
            }
            TemplateMatch[] matchings = tm.ProcessImage(image1, image2, new Rectangle(new Point(0, 0), new Size(250, 250)));
            if (matchings[0].Similarity > 0.8f)
            {
                int idDocumentos = Convert.ToInt32(datos.SelectValor("select count(*) from Documentos")) + 1;
                if (dropCategoria.SelectedValue == "InfoPersonal")
                {
                    // Son Similares
                    this.Response.Write("<script language='JavaScript'>window.alert('la imagen se subio correctamente')</script>");
                    Imagen.SaveFile(Server.MapPath(@"imagenes").ToString() + @"\InfoPersonal\" + selectedTipo + "_" + Session["userName"] + "_" + "Scan.png");
                    string idEmpleado = datos.SelectValor("select idEmpleado from Empleado where correoElectronico='" + Session["userName"] + "'");
                    datos.Comand("insert into Documentos values(" + idDocumentos + "," + idEmpleado + ",'" + selectedTipo + "','" + dropCategoria.SelectedValue + "','" + Server.MapPath(@"imagenes").ToString() + @"\InfoPersonal\" + selectedTipo + "_" + Session["userName"] + "_" + "Scan.png" + "')");
                }
                else if (dropCategoria.SelectedValue == "InfoAcademica")
                {
                    this.Response.Write("<script language='JavaScript'>window.alert('la imagen se subio correctamente')</script>");
                    Imagen.SaveFile(Server.MapPath(@"imagenes").ToString() + @"\InfoAcademica\" + selectedTipo + "_" + Session["userName"] + "_" + "Scan.png");
                    string idEmpleado = datos.SelectValor("select idEmpleado from Empleado where correoElectronico='" + Session["userName"] + "'");
                    datos.Comand("insert into Documentos values(" + idDocumentos + "," + idEmpleado + ",'" + selectedTipo + "','" + dropCategoria.SelectedValue + "','" + Server.MapPath(@"imagenes").ToString() + @"\InfoAcademica\" + selectedTipo + "_" + Session["userName"] + "_" + "Scan.png" + "')");
                }
                else if (dropCategoria.SelectedValue == "InfoLaboral")
                {
                    this.Response.Write("<script language='JavaScript'>window.alert('la imagen se subio correctamente')</script>");
                    Imagen.SaveFile(Server.MapPath(@"imagenes").ToString() + @"\InfoLaboral\" + selectedTipo + "_" + Session["userName"] + "_" + "Scan.png");
                    string idEmpleado = datos.SelectValor("select idEmpleado from Empleado where correoElectronico='" + Session["userName"] + "'");
                    datos.Comand("insert into Documentos values(" + idDocumentos + "," + idEmpleado + ",'" + selectedTipo + "','" + dropCategoria.SelectedValue + "','" + Server.MapPath(@"imagenes").ToString() + @"\InfoLaboral\" + selectedTipo + "_" + Session["userName"] + "_" + "Scan.png" + "')");
                }
            }
            else
            {
                //No son similares
                this.Response.Write("<script language='JavaScript'>window.alert('la imagen que subiste no coincide con el tipo de archivo que seleccionaste')</script>");
                Image1.ImageUrl = "";
            }
        }
Exemplo n.º 16
0
        private void DoScan()
        {
            WIA.Item         item            = default(WIA.Item);
            WIA.ImageFile    Img             = default(WIA.ImageFile);
            WIA.CommonDialog WiaCommonDialog = new CommonDialogClass();
            bool             hasMorePages    = true;
            int    x           = 0;
            int    numPages    = 0;
            string ImgMain     = null;
            string ImgMainName = null;

            try
            {
                if (treealfresco.SelectedNode == null)
                {
                    MessageBox.Show("Please select a Space to store your data into", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                ResultSetRowNode node = (ResultSetRowNode)treealfresco.SelectedNode.Tag;
                LocationUuid = node.id;

                LocationName = treealfresco.SelectedNode.Text;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            while (hasMorePages)
            {
                //Create DeviceManager
                DeviceManager manager = new DeviceManagerClass();
                Device        WiaDev  = null;
                foreach (DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == this.DeviceID)
                    {
                        WIA.Properties infoprop = null;
                        infoprop = info.Properties;
                        //connect to scanner
                        WiaDev = info.Connect();
                        break; // TODO: might not be correct. Was : Exit For
                    }
                }

                //Start Scan

                Img = null;

                item = WiaDev.Items[1] as WIA.Item;

                try
                {
                    Img = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatTIFF, false);

                    //process image:
                    //one would do image processing here

                    //Save to file
                    string jpegGuid = null;
                    //retrieves jpegKey from registry, used in saving JPEG
                    Microsoft.Win32.RegistryKey jpegKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\{D2923B86-15F1-46FF-A19A-DE825F919576}\\SupportedExtension\\.jpg");
                    jpegGuid = (string)jpegKey.GetValue("FormatGUID");
                    //loops through available formats for the captured item, looking for the JPG format
                    foreach (string format in item.Formats)
                    {
                        if ((format == jpegGuid))
                        {
                            //transfers image to an imagefile object
                            Img = (WIA.ImageFile)item.Transfer(WIA.FormatID.wiaFormatTIFF);
                            int Counter = 0;
                            //counter in loop appended to filename
                            bool LoopAgain = true;
                            //searches directory, gets next available picture name
                            while (!(LoopAgain == false))
                            {
                                string File = SavePath + "\\";
                                File += txtPrefix.Text;
                                File += Counter;
                                File += ".tiff";
                                string Filename = txtPrefix.Text;
                                Filename += Counter;
                                Filename += ".tiff";


                                if (System.IO.File.Exists(Filename))
                                {
                                    //file exists, delete it
                                    System.IO.File.Delete(Filename);
                                }
                                if (numPages == 0)
                                {
                                    Img.SaveFile(Filename);
                                }
                                ImgMain     = File;
                                ImgMainName = Filename;
                                if (numPages > 0)
                                {
                                    int y = Counter;
                                    y            = Counter - 1;
                                    ImgMain      = SavePath + "\\";
                                    ImgMain     += txtPrefix.Text;
                                    ImgMain     += y;
                                    ImgMain     += ".tiff";
                                    ImgMainName  = txtPrefix.Text;
                                    ImgMainName += y;
                                    ImgMainName += ".tiff";
                                    //createtiff(ImgMain, File);
                                }
                                numPages += 1;

                                Counter = Counter + 1;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
                finally
                {
                    item = null;
                    //determine if there are any more pages waiting
                    WIA.Property documentHandlingSelect = null;
                    WIA.Property documentHandlingStatus = null;
                    foreach (WIA.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;
                    UploadNow(ImgMainName, ImgMain);
                    MessageBox.Show(ImgMain + " uploaded");
                    //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 += 1;
                }
            }
        }
Exemplo n.º 17
0
        private void btncapture_Click(object sender, EventArgs e)
        {
            if (treealfresco.SelectedNode == null)
            {
                MessageBox.Show("Please select a Space to store your data into", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //exit btncapture_Click;
            }

            if (rdscanner.Checked == true)
            {
                Enabled = false;

                _settings = new ScanSettings()
                {
                    UseDocumentFeeder = useAdfCheckBox.Checked,
                    ShowTwainUI       = useUICheckBox.Checked,
                    Resolution        = blackAndWhiteCheckBox.Checked
                        ? ResolutionSettings.Fax
                        : ResolutionSettings.ColourPhotocopier
                };

                try
                {
                    _twain.StartScanning(_settings);
                }
                catch (TwainException ex)
                {
                    MessageBox.Show(ex.Message);
                    Enabled = true;
                }
            }
            else
            {
                WIA.Item         item            = default(WIA.Item);
                WIA.CommonDialog WiaCommonDialog = new CommonDialogClass();
                try
                {
                    //Check if the device is scanner or not
                    if (rdscanner.Checked == true)
                    {
                        //scans the image using the Scanner only (ADF or Flatbed)
                        DoScan();
                    }
                    else
                    {
                        item = SelectedDevice.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture);
                    }
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Problem Taking Picture. Please make sure that the camera is plugged in and is not in use by another application. " + "\r\n" + "Extra Info:" + ex.Message, "Problem Grabbing Picture", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                    return;
                }

                try
                {
                    //Validate if a image location is selected or not
                    if (treealfresco.SelectedNode == null)
                    {
                        MessageBox.Show("Please select a Space to store your data into", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    ResultSetRowNode node = (ResultSetRowNode)treealfresco.SelectedNode.Tag;
                    LocationUuid = node.id;

                    LocationName = treealfresco.SelectedNode.Text;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

                try
                {
                    //Executes the device's TakePicture command based on selected image format
                    if (rdjpeg.Checked == true)
                    {
                        string jpegGuid = null;
                        //retrieves jpegKey from registry, used in saving JPEG
                        Microsoft.Win32.RegistryKey jpegKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\{D2923B86-15F1-46FF-A19A-DE825F919576}\\SupportedExtension\\.jpg");
                        jpegGuid = (string)jpegKey.GetValue("FormatGUID");
                        //loops through available formats for the captured item, looking for the JPG format
                        foreach (string format in item.Formats)
                        {
                            if ((format == jpegGuid))
                            {
                                //transfers image to an imagefile object
                                WIA.ImageFile imagefile = (WIA.ImageFile)item.Transfer(format);
                                int           Counter   = 0;
                                //counter in loop appended to filename
                                bool LoopAgain = true;
                                //searches directory, gets next available picture name
                                while (!(LoopAgain == false))
                                {
                                    string File = SavePath + "\\";
                                    File += txtPrefix.Text;
                                    File += Counter;
                                    File += ".jpg";
                                    string Filename = txtPrefix.Text;
                                    Filename += Counter;
                                    Filename += ".jpg";
                                    //if file doesnt exist, save the file
                                    if (!System.IO.File.Exists(Filename))
                                    {
                                        SavedFilePath = Filename;
                                        imagefile.SaveFile(Filename);
                                        //saves file to disk
                                        //Upload the file to Alfresco
                                        UploadNow(Filename, File);
                                        MessageBox.Show(File + " uploaded");
                                        LoopAgain = false;
                                    }
                                    Counter = Counter + 1;
                                }
                            }
                        }
                    }
                    else if (rdgif.Checked == true)
                    {
                        string jpegGuid = null;
                        //retrieves jpegKey from registry, used in saving JPEG
                        Microsoft.Win32.RegistryKey jpegKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\{D2923B86-15F1-46FF-A19A-DE825F919576}\\SupportedExtension\\.jpg");
                        jpegGuid = (string)jpegKey.GetValue("FormatGUID");
                        //loops through available formats for the captured item, looking for the JPG format
                        foreach (string format in item.Formats)
                        {
                            if ((format == jpegGuid))
                            {
                                //transfers image to an imagefile object
                                WIA.ImageFile imagefile = (WIA.ImageFile)item.Transfer(WIA.FormatID.wiaFormatGIF);
                                int           Counter   = 0;
                                //counter in loop appended to filename
                                bool LoopAgain = true;
                                //searches directory, gets next available picture name
                                while (!(LoopAgain == false))
                                {
                                    string File = SavePath + "\\";
                                    File += txtPrefix.Text;
                                    File += Counter;
                                    File += ".gif";
                                    string Filename = txtPrefix.Text;
                                    Filename += Counter;
                                    Filename += ".gif";
                                    //if file doesnt exist, save the file
                                    if (!System.IO.File.Exists(Filename))
                                    {
                                        SavedFilePath = Filename;
                                        imagefile.SaveFile(Filename);
                                        //saves file to disk
                                        // Upload the file to Alfresco
                                        UploadNow(Filename, File);
                                        MessageBox.Show(File + " uploaded");
                                        LoopAgain = false;
                                    }
                                    Counter = Counter + 1;
                                }
                            }
                        }
                    }
                    else if (rdtiff.Checked == true)
                    {
                        string jpegGuid = null;
                        //retrieves jpegKey from registry, used in saving JPEG
                        Microsoft.Win32.RegistryKey jpegKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\{D2923B86-15F1-46FF-A19A-DE825F919576}\\SupportedExtension\\.jpg");
                        jpegGuid = (string)jpegKey.GetValue("FormatGUID");
                        //loops through available formats for the captured item, looking for the JPG format
                        foreach (string format in item.Formats)
                        {
                            if ((format == jpegGuid))
                            {
                                //transfers image to an imagefile object
                                WIA.ImageFile imagefile = (WIA.ImageFile)item.Transfer(WIA.FormatID.wiaFormatTIFF);
                                int           Counter   = 0;
                                //counter in loop appended to filename
                                bool LoopAgain = true;
                                //searches directory, gets next available picture name
                                while (!(LoopAgain == false))

                                {
                                    string File = SavePath + "\\";
                                    File += txtPrefix.Text;
                                    File += Counter;
                                    File += ".tiff";
                                    string Filename = txtPrefix.Text;
                                    Filename += Counter;
                                    Filename += ".tiff";
                                    //if file doesnt exist, save the file
                                    if (!System.IO.File.Exists(Filename))
                                    {
                                        SavedFilePath = Filename;
                                        imagefile.SaveFile(Filename);
                                        //saves file to disk
                                        UploadNow(Filename, File);
                                        MessageBox.Show(File + " uploaded");
                                        LoopAgain = false;
                                    }
                                    Counter = Counter + 1;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Scan Page,
        /// </summary>
        /// <param name="wia">Connected Device</param>
        /// <param name="pageSize">Page Size. A4, A3, A2 Etc</param>
        /// <param name="RotatePage">Rotation of page while scanning</param>
        public void Scan(PageSize pageSize, bool rotatePage, int DPI, string filepath, bool useAdf, bool duplex)
        {
            int  pages        = 0;
            bool hasMorePages = false;

            WIA.CommonDialog WiaCommonDialog = new WIA.CommonDialog();

            try
            {
                do
                {
                    //Connect to Device
                    Device   wia  = Connect();
                    WIA.Item item = wia.Items[1] as WIA.Item;

                    //Setup ADF
                    if ((useAdf) || (duplex))
                    {
                        SetupADF(wia, duplex);
                    }

                    //Setup Page Size
                    SetupPageSize(wia, rotatePage, pageSize, DPI, item);

                    WIA.ImageFile imgFile        = null;
                    WIA.ImageFile imgFile_duplex = null; //if duplex is setup, this will be back page


                    imgFile = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false);

                    //If duplex page, get back page now.
                    if (duplex)
                    {
                        imgFile_duplex = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false);
                    }

                    string varImageFileName = filepath + "\\Scanned-" + pages.ToString() + ".jpg";
                    Delete_File(varImageFileName); //if file already exists. delete it.
                    imgFile.SaveFile(varImageFileName);

                    string varImageFileName_duplex;

                    if (duplex)
                    {
                        varImageFileName_duplex = filepath + "\\Scanned-" + pages++.ToString() + ".jpg";
                        Delete_File(varImageFileName_duplex); //if file already exists. delete it.
                        imgFile_duplex.SaveFile(varImageFileName);
                    }

                    //Check with scanner to see if there are more pages.
                    if (useAdf || duplex)
                    {
                        hasMorePages = HasMorePages(wia);
                        pages++; @
                    }
                } while (hasMorePages);
            }
            catch (COMException ex)
            {
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerName"></param>
        /// <returns>Scanned images path.</returns>
        public static List <string> Scan(string scannerId, DoWorkEventArgs e)
        {
            List <string> images       = new List <string>();
            bool          hasMorePages = true;
            ITempFilesResource <ImageFile> tempFiles = TempFilesScannerResource <ImageFile> .DefaultInstance();

            while (hasMorePages && !e.Cancel)
            {
                // select the correct scanner using the provided scannerId parameter
                WIA.DeviceManager manager = new WIA.DeviceManager();
                WIA.Device        device  = null;
                foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == scannerId)
                    {
                        // connect to scanner
                        device = info.Connect();
                        break;
                    }
                }
                // device was not found
                if (device == null)
                {
                    // enumerate available devices
                    string availableDevices = "";
                    foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                    {
                        availableDevices += info.DeviceID + "\n";
                    }
                    // show error with available devices
                    throw new Exception("The device with provided ID could not be found. Available Devices:\n" + availableDevices);
                }
                WIA.Item item = device.Items[1] as WIA.Item;
                try
                {
                    // scan image
                    WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
                    WIA.ImageFile     image           = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);
                    // save to temp file
                    string fileName = tempFiles.SaveFile(image);
                    image = null;
                    // add file to output list
                    images.Add(fileName);
                }
                catch (System.Runtime.InteropServices.COMException exc)
                {
                    Debug.WriteLine(exc.Message);
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc.Message);
                }
                finally
                {
                    item = null;
                    //determine if there are any more pages waiting
                    WIA.Property documentHandlingSelect = null;
                    WIA.Property documentHandlingStatus = null;
                    foreach (WIA.Property prop in device.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;
                        }
                    }
                    // assume there are no more pages
                    hasMorePages = false;
                    // may not exist on flatbed scanner but required for feeder
                    if (documentHandlingSelect != null)
                    {
                        // 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);
                        }
                    }
                }
            }
            if (!e.Cancel)
            {
                return(images);
            }
            else
            {
                foreach (var image in images)
                {
                    tempFiles.DeleteFile(image);
                }
                images.Clear();
                return(images);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Scan Page,
        /// </summary>
        /// <param name="wia">Connected Device</param>
        /// <param name="pageSize">Page Size. A4, A3, A2 Etc</param>
        /// <param name="RotatePage">Rotation of page while scanning</param>
        public void Scan(bool rotatePage, int DPI, string filepath, bool useAdf, bool duplex)  //PageSize pageSize,
        {
            int  pages        = 0;
            bool hasMorePages = false;

            string[] sourceFiles = new string[100];

            WIA.CommonDialog WiaCommonDialog = new WIA.CommonDialog();

            try
            {
                do
                {
                    //  Connect to Device
                    Device   wia  = Connect();
                    WIA.Item item = wia.Items[1] as WIA.Item;

                    //  Setup ADF
                    if ((useAdf) || (duplex))
                    {
                        SetupADF(wia, duplex);
                    }

                    //  Setup Page Size
                    //  SetupPageSize(wia, rotatePage, A4, DPI, item);

                    WIA.ImageFile imgFile        = null;
                    WIA.ImageFile imgFile_duplex = null; //  if duplex is setup, this will be back page

                    imgFile = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false);

                    //  If duplex page, get back page now.
                    if (duplex)
                    {
                        imgFile_duplex = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false);
                    }

                    string varImageFileName = filepath + "\\Scanned" + ".jpeg";

                    Delete_File(varImageFileName); //  if file already exists. delete it.
                    imgFile.SaveFile(varImageFileName);

                    using (var src = new System.Drawing.Bitmap(varImageFileName))
                        using (var bmp = new System.Drawing.Bitmap(1000, 1000, System.Drawing.Imaging.PixelFormat.Format32bppPArgb))
                            using (var gr = System.Drawing.Graphics.FromImage(bmp))
                            {
                                gr.Clear(System.Drawing.Color.Blue);
                                gr.DrawImage(src, new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height));
                                gr.DrawString("This is vivek", new System.Drawing.Font("Arial", 15, System.Drawing.FontStyle.Regular), System.Drawing.SystemBrushes.WindowText, new System.Drawing.Point(550, 20));
                                bmp.Save(System.Configuration.ConfigurationSettings.AppSettings["Path"] + "test" + pages + ".jpeg", System.Drawing.Imaging.ImageFormat.Png);

                                ////string imgPath = "test" + pages + ".tiff";
                                ////sourceFiles[pages] = imgPath;
                                //mergeTiffPages(string str_DestinationPath, string[] sourceFiles)
                            }
                    MergeTiffPages(@"D:\Test\", sourceFiles);

                    string varImageFileName_duplex;

                    if (duplex)
                    {
                        varImageFileName_duplex = filepath + "\\Scanned-" + pages.ToString() + ".tiff";
                        Delete_File(varImageFileName_duplex); //if file already exists. delete it.
                        imgFile_duplex.SaveFile(varImageFileName);
                    }

                    //Check with scanner to see if there are more pages.
                    if (useAdf || duplex)
                    {
                        hasMorePages = HasMorePages(wia);
                        pages++;
                    }
                }while (hasMorePages);
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                //throw new System.Exception(CheckError((uint)ex.ErrorCode));
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerName"></param>
        /// <returns>Scanned images.</returns>
        public static List <Image> Scan(string scannerId)
        {
            List <Image> images       = new List <Image>();
            bool         hasMorePages = true;

            while (hasMorePages)
            {
                // select the correct scanner using the provided scannerId parameter
                WIA.DeviceManager manager = new WIA.DeviceManager();
                WIA.Device        device  = null;
                foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == scannerId)
                    {
                        // connect to scanner
                        device = info.Connect();
                        break;
                    }
                }
                // device was not found
                if (device == null)
                {
                    // enumerate available devices
                    string availableDevices = "";
                    foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                    {
                        availableDevices += info.DeviceID + "\n";
                    }
                    // show error with available devices
                    throw new Exception("The device with provided ID could not be found." +
                                        "Available Devices:\n" + availableDevices);
                }

                // Set color intent to greyscale if user requested it
                if (clrMode == Utils.ColorMode.Greyscale)
                {
                    Property prop = device.Items[1].Properties.get_Item("6146");
                    prop.set_Value(2); //4 is Black-white,gray is 2, color 1 (Color Intent)
                }

                WIA.Item item = device.Items[1] as WIA.Item;

                try
                {
                    // scan image
                    WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
                    WIA.ImageFile     image           = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);
                    // save to temp file
                    string fileName = Utils.GetNextFileName(scannedDocumentsPath + "\\NumérisationSansTitre.bmp");
                    //File.Delete(fileName);
                    image.SaveFile(fileName);
                    image = null;
                    // add file to output list
                    images.Add(Image.FromFile(fileName));
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                finally
                {
                    item = null;
                    //determine if there are any more pages waiting
                    WIA.Property documentHandlingSelect = null;
                    WIA.Property documentHandlingStatus = null;
                    foreach (WIA.Property prop in device.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;
                        }
                    }
                    // assume there are no more pages
                    hasMorePages = false;
                    // may not exist on flatbed scanner but required for feeder
                    if (documentHandlingSelect != null)
                    {
                        // 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);
                        }
                    }
                }
            }
            return(images);
        }
Exemplo n.º 22
0
        public ArrayList ADFScan()
        {
            ArrayList dataArray = new ArrayList();

            //Choose Scanner
            CommonDialogClass class1 = new CommonDialogClass();
            //

            //class1.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false);
            //
            Device d = class1.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false);

            if (d != null)
            {
                this.DeviceID = d.DeviceID;
            }
            else
            {
                //no scanner chosen
                return(new ArrayList());
            }



            WIA.CommonDialog WiaCommonDialog = new CommonDialogClass();

            bool hasMorePages = true;
            int  x            = 0;
            int  numPages     = 0;

            while (hasMorePages)
            {
                //Create DeviceManager
                DeviceManager manager = new DeviceManagerClass();
                Device        WiaDev  = null;
                foreach (DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == this.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;

                try
                {
                    img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, wiaFormatJPEG, false);


                    //process image:
                    //one would do image processing here
                    //
                    dataArray.Add(img);
                    //Save to file
                    //string varImageFileName = "c:\\test" + x.ToString() + ".jpg";
                    // if (File.Exists(varImageFileName))
                    // {
                    //     //file exists, delete it
                    //     File.Delete(varImageFileName);
                    // }
                    // img.SaveFile(varImageFileName);
                    numPages++;
                    img = null;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
                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++;
                }
            }
            return(dataArray);
        }
Exemplo n.º 23
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);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Setup Page Size
        /// </summary>
        /// <param name="wia"></param>
        private void SetupPageSize(Device wia, bool rotatePage, PageSize pageSize, int DPI, WIA.Item item)
        {
            //Setup Page Size Property
            foreach (WIA.Property itemProperty in item.Properties)
            {
                if (itemProperty.Name.Equals("Horizontal Resolution"))
                {
                    ((IProperty)itemProperty).set_Value(DPI);
                }
                else if (itemProperty.Name.Equals("Vertical Resolution"))
                {
                    ((IProperty)itemProperty).set_Value(DPI);
                }
                else if (itemProperty.Name.Equals("Horizontal Extent"))
                {
                    double extent = DPI * pageSize.Height;

                    if (rotatePage)
                    {
                        extent = DPI * pageSize.Width;
                    }

                    ((IProperty)itemProperty).set_Value(extent);
                }
                else if (itemProperty.Name.Equals("Vertical Extent"))
                {
                    double extent = DPI * pageSize.Width;

                    if (rotatePage)
                    {
                        extent = pageSize.Height * DPI;
                    }

                    ((IProperty)itemProperty).set_Value(extent);
                }
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerName"></param>
        /// <returns>Scanned images.</returns>
        public static List <Image> Scan(string scannerId, int pages, WIAScanQuality quality, WIAPageSize pageSize, DocumentSource source)
        {
            List <Image> images       = new List <Image>();
            bool         hasMorePages = true;
            int          numbrPages   = pages;

            while (hasMorePages)
            {
                // select the correct scanner using the provided scannerId parameter
                WIA.DeviceManager manager = new WIA.DeviceManager();
                WIA.Device        device  = null;
                foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == scannerId)
                    {
                        // connect to scanner
                        device = info.Connect();
                        break;
                    }
                }
                // device was not found
                if (device == null)
                {
                    // enumerate available devices
                    string availableDevices = "";
                    foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                    {
                        availableDevices += info.DeviceID + "\n";
                    }

                    // show error with available devices
                    throw new Exception("The device with provided ID could not be found. Available Devices:\n" + availableDevices);
                }
                SetWIAProperty(device.Properties, WIA_DEVICE_PROPERTY_PAGES_ID, 1);
                SetWIAProperty(device.Properties, WIA_DEVICE_SOURCE_SELECT_ID, source);

                WIA.Item item = device.Items[1] as WIA.Item;

                // adjust the scan settings
                int dpi;
                int width_pixels;
                int height_pixels;
                switch (quality)
                {
                case WIAScanQuality.Final:
                    dpi = 300;
                    break;

                default:
                    throw new Exception("Unknown WIAScanQuality: " + quality.ToString());
                }
                switch (pageSize)
                {
                case WIAPageSize.A4:
                    width_pixels  = (int)(8.3f * dpi);
                    height_pixels = (int)(11.7f * dpi);
                    break;

                case WIAPageSize.Letter:
                    width_pixels  = (int)(8.5f * dpi);
                    height_pixels = (int)(11f * dpi);
                    break;

                case WIAPageSize.Legal:
                    width_pixels  = (int)(8.5f * dpi);
                    height_pixels = (int)(14f * dpi);
                    break;

                default:
                    throw new Exception("Unknown WIAPageSize: " + pageSize.ToString());
                }

                AdjustScannerSettings(item, dpi, 0, 0, width_pixels, height_pixels, 0, 0, 1);

                try
                {
                    // scan image
                    WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
                    WIA.ImageFile     image           = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);

                    // save to temp file
                    string fileName = Path.GetTempFileName();
                    File.Delete(fileName);
                    image.SaveFile(fileName);
                    image = null;
                    // add file to output list
                    images.Add(Image.FromFile(fileName));
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                finally
                {
                    item = null;
                    //determine if there are any more pages waiting
                    WIA.Property documentHandlingSelect = null;
                    WIA.Property documentHandlingStatus = null;
                    foreach (WIA.Property prop in device.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;
                        }
                    }
                    // assume there are no more pages
                    hasMorePages = false;
                    // may not exist on flatbed scanner but required for feeder
                    if (documentHandlingSelect != null)
                    {
                        // 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);
                        }
                    }
                }
                numbrPages -= 1;
                if (numbrPages > 0)
                {
                    hasMorePages = true;
                }
                else
                {
                    hasMorePages = false;
                }
            }
            return(images);
        }
Exemplo n.º 26
0
        private void Btn_scan_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender != null)
                {
                    SectionData.StartAwait(grid_main);
                }

                CommonDialogClass commonDialogClass = new CommonDialogClass();
                Device            scannerDevice     = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false);
                if (scannerDevice != null)
                {
                    WIA.Item scannnerItem = scannerDevice.Items[1];
                    AdjustScannerSettings(scannnerItem, 600, 0, 0, 1010, 620, 0, 0);
                    object scanResult = commonDialogClass.ShowTransfer(scannnerItem, WIA.FormatID.wiaFormatPNG, false);
                    if (scanResult != null)
                    {
                        ImageFile image = (ImageFile)scanResult;

                        var imageBytes  = (byte[])image.FileData.get_BinaryData();// <-- Converts the ImageFile to a byte array
                        var bitmapImage = new BitmapImage();
                        if (imageBytes != null)
                        {
                            using (var memoryStream = new MemoryStream(imageBytes))
                            {
                                bitmapImage.BeginInit();
                                bitmapImage.CacheOption  = BitmapCacheOption.OnLoad;
                                bitmapImage.StreamSource = memoryStream;
                                bitmapImage.EndInit();
                            }

                            img_upload.Background = new ImageBrush(bitmapImage);
                        }
                        // configure trmporery path
                        //string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
                        string dir     = Directory.GetCurrentDirectory();
                        string tmpPath = System.IO.Path.Combine(dir, Global.ScannedImageLocation);
                        if (System.IO.File.Exists(tmpPath))
                        {
                            System.IO.File.Delete(tmpPath);
                        }
                        SaveImageToJpgFile(image, tmpPath);
                        openFileDialog.FileName = tmpPath;
                    }
                }

                if (sender != null)
                {
                    SectionData.EndAwait(grid_main);
                }
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                if (sender != null)
                {
                    SectionData.EndAwait(grid_main);
                }
                System.Windows.MessageBox.Show("Problem with scanning device. Please ensure that the scanner is properly connected and switched on", "Inweon Grain Management System");
            }
        }