Ejemplo n.º 1
1
 public static List<System.Drawing.Image> preScan()
 {
     WIA.ICommonDialog dialog = new WIA.CommonDialog();
     WIA.Device device = dialog.ShowSelectDevice(WIA.WiaDeviceType.UnspecifiedDeviceType, true, false);
     if (device != null)
     {
         return preScan(device.DeviceID);
     }
     else
     {
         throw new Exception("You must select a device for scanning.");
     }
 }
Ejemplo n.º 2
0
        private void set_scaner_Click(object sender, RoutedEventArgs e)
        {
            CommonDialog dialog = new WIA.CommonDialog();

            default_device = dialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);
            DeviceInfo dev_ifo = null;
            //dev_ifo.Properties.
            //Device.Text =
        }
Ejemplo n.º 3
0
 private void loadScanner()
 {
     wia_dialog = new WIA.CommonDialog();
     scanner    = wia_dialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false);
     if (scanner == null)
     {
         MessageBox.Show("Nie wykryto skanera");
     }
 }
Ejemplo n.º 4
0
        public void GetDefaultDeviceID()
        {
            // Select a scanner
            WIA.CommonDialog wiaDiag = new WIA.CommonDialog();
            Device           d       = wiaDiag.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);

            if (d != null)
            {
                this.DeviceId = d.DeviceID;
                FindDevice();
                this._device = this.deviceInfo.Connect();
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Use scanner to scan an image (with user selecting the scanner from a dialog).
 /// </summary>
 /// <returns>Scanned images.</returns>
 public static List <Image> Scan()
 {
     WIA.ICommonDialog dialog = new WIA.CommonDialog();
     WIA.Device        device = dialog.ShowSelectDevice(WIA.WiaDeviceType.UnspecifiedDeviceType, true, false);
     if (device != null)
     {
         return(Scan(device.DeviceID));
     }
     else
     {
         throw new Exception("You must select a device for scanning.");
     }
 }
Ejemplo n.º 6
0
        private void deviceInfoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WIA.ICommonDialog commonDialogClass = new WIA.CommonDialog();
            Device            scannerDevice     = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false);
            Item   scannnerItem = scannerDevice.Items[1];
            String str          = "";

            foreach (Property prop in scannnerItem.Properties)
            {
                str += "\n" + prop.Name + " " + prop.PropertyID + " " + prop.get_Value();
            }
            MessageBox.Show(str, "Device Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Ejemplo n.º 7
0
 public static List <Image> Scan(WIAScanQuality scanQuality, WIAPageSize pageSize, DocumentSource source)
 {
     WIA.ICommonDialog dialog = new WIA.CommonDialog();
     WIA.Device        device = dialog.ShowSelectDevice(WIA.WiaDeviceType.UnspecifiedDeviceType, true, false);
     if (device != null)
     {
         return(Scan(device.DeviceID, 1, scanQuality, pageSize, source));
     }
     else
     {
         throw new Exception("You must select a device for scanning.");
     }
 }
Ejemplo n.º 8
0
 /// <summary>
 /// Use scanner to scan an image (with user selecting the scanner from a dialog).
 /// </summary>
 /// <returns>Scanned images.</returns>
 public static List <System.Drawing.Image> AutoScan(IItem scannnerItem, int scanResolutionDPI, double scanStartLeftPixel, double scanStartTopPixel,
                                                    double scanWidthPixels, double scanHeightPixels, int brightnessPercents, int contrastPercents, int colorMode)
 {
     WIA.ICommonDialog dialog = new WIA.CommonDialog();
     WIA.Device        device = dialog.ShowSelectDevice(WIA.WiaDeviceType.UnspecifiedDeviceType, true, false);
     if (device != null)
     {
         return(AutoScan(device.DeviceID, scanResolutionDPI, scanStartLeftPixel, scanStartTopPixel,
                         scanWidthPixels, scanHeightPixels, brightnessPercents, contrastPercents, colorMode));
     }
     else
     {
         throw new Exception("You must select a device for scanning.");
     }
 }
Ejemplo n.º 9
0
        private string FindDefaultDeviceId()
        {
            if (String.IsNullOrEmpty(deviceId))
            {
                // Select a scanner  
                WIA.CommonDialog wiaDiag = new WIA.CommonDialog();
                Device d = wiaDiag.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);
                if (d != null)
                {
                    deviceId = d.DeviceID;

                }
            }
            return deviceId;
        }
Ejemplo n.º 10
0
 public static Device SelectDevice()
 {
     WIA.ICommonDialog dialog = new WIA.CommonDialog();
     try
     {
         WIA.Device device = dialog.ShowSelectDevice
                                 (WIA.WiaDeviceType.ScannerDeviceType, true, false);
         return(device);
     }
     catch (System.Runtime.InteropServices.COMException ex)
     {
         Debug.WriteLine(ex.Message);
         return(null);
     }
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Use scanner to scan an image (with user selecting the scanner from a dialog).
        /// </summary>
        /// <returns>Scanned images. (Base64 strings)</returns>
        public static List <string> Scan()
        {
            WIA.ICommonDialog dialog   = new WIA.CommonDialog();
            WIA.Device        device   = dialog.ShowSelectDevice(WIA.WiaDeviceType.UnspecifiedDeviceType, true, false);
            ScanSettings      settings = new ScanSettings();

            settings.DeviceId = device.DeviceID;
            if (device != null)
            {
                return(Scan(settings));
            }
            else
            {
                throw new Exception("You must select a device for scanning.");
            }
        }
Ejemplo n.º 12
0
        public List <Image> start()
        {
            List <Image> imageLost = new List <Image>();

            WIA.CommonDialog dialog = new WIA.CommonDialog();
            WIA.Device       device = dialog.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType);
            WIA.Items        items  = dialog.ShowSelectItems(device);
            WIA.ImageFile    image  = null;
            dialog = new WIA.CommonDialog();
            foreach (WIA.Item item in items)
            {
                while (true)
                {
                    Console.WriteLine(device.Commands);

                    try
                    {
                        if (stop == true)
                        {
                            image = null;
                            stop  = false;
                        }
                        else
                        {
                            image = (WIA.ImageFile)dialog.ShowTransfer(item, "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}", false);
                        }
                        if ((image != null) && (image.FileData != null))
                        {
                            WIA.Vector vector = image.FileData;
                            imageLost.Add(Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData())));
                        }
                    }
                    catch (System.Runtime.InteropServices.COMException)
                    {
                        return(imageLost);
                    }
                    finally
                    {
                        if (image != null)
                        {
                            Marshal.FinalReleaseComObject(image);
                        }
                    }
                }
            }
            return(imageLost);
        }
Ejemplo n.º 13
0
 private bool chooseDevice()
 {
     try
     {
         Scanner = Dialog1.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, true, true);
         if (Scanner != null)
         {
             return(true);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Błąd ! Nie wybrano skanera " + ex.Message, "Wybierz urządzenie",
                         MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     return(false);
 }
Ejemplo n.º 14
0
 private bool SelectDevice()
 {
     try
     {
         // ISSUE: variable of a compiler-generated type
         WIA.CommonDialog commonDialog = (WIA.CommonDialog)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("850D1D11-70F3-4BE5-9A11-77AA6B2BB201")));
         // ISSUE: reference to a compiler-generated method
         // ISSUE: variable of a compiler-generated type
         Device device = commonDialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, true);
         this._deviceId = device.DeviceID;
     }
     catch (Exception ex)
     {
         Console.Error.WriteLine("Failed to select scanner");
         Console.Error.WriteLine(ex.ToString());
     }
     return(!string.IsNullOrEmpty(this._deviceId));
 }
Ejemplo n.º 15
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);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Select Scanner.
        /// If you need to save the Scanner, Save WiaWrapper.DeviceID
        /// </summary>
        public void SelectScanner()
        {
            WIA.CommonDialog wiaDiag = new WIA.CommonDialog();

            try
            {
                Device d = wiaDiag.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false);
                if (d != null)
                {
                    DeviceID = d.DeviceID;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error, Is a scanner chosen?");
            }

            throw new Exception("No Device Selected");
        }
        private void btn_scannen_Click(object sender, EventArgs e)
        {
            if (rdb_spl.Checked)
            {
                btn_scannen.Enabled      = false;
                tbx_name.Enabled         = false;
                tbx_bemerkung.Enabled    = false;
                dtp_datum.Enabled        = false;
                lbx_dokument_typ.Enabled = false;
                string           wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
                WIA.CommonDialog cd            = new WIA.CommonDialog();
                WIA.Device       dev           = null;
                dev = cd.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);
                dev.Properties["Pages"].set_Value(1);
                //dev.Properties["3088"].set_Value(5);
                Item dt = dev.Items[1];
                dt.Properties["6147"].set_Value(300);
                dt.Properties["6148"].set_Value(300);
                try
                {
                    int counter = -1;
                    while (true)
                    {
                        counter++;
                        WIA.CommonDialog common = new WIA.CommonDialog();
                        ImageFile        image  = common.ShowTransfer(dev.Items[1], wiaFormatJPEG, true);
                        pfad = Hauptfenster.tempo_pfad + @"\" + tbx_name.Text + counter.ToString() + ".jpg";
                        Byte[]               imageBytes = (byte[])image.FileData.get_BinaryData();
                        MemoryStream         ms         = new MemoryStream(imageBytes);
                        System.Drawing.Image img        = System.Drawing.Image.FromStream(ms);
                        JpegBildKomprimieren(img, int.Parse(textBox1.Text), pfad);
                        //image.SaveFile(pfad);
                    }
                }
                catch (Exception)
                {
                }
                btn_erstellen.Enabled = true;
            }
            else if (rdb_dpl.Checked)
            {
                btn_scannen.Enabled      = false;
                tbx_name.Enabled         = false;
                tbx_bemerkung.Enabled    = false;
                dtp_datum.Enabled        = false;
                lbx_dokument_typ.Enabled = false;
                string           wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
                WIA.CommonDialog cd            = new WIA.CommonDialog();
                WIA.Device       dev           = null;
                dev = cd.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);
                dev.Properties["Pages"].set_Value(1);
                //dev.Properties["3088"].set_Value(5);
                Item dt = dev.Items[1];
                dt.Properties["6147"].set_Value(300);
                dt.Properties["6148"].set_Value(300);
                int counter = -1;
                try
                {
                    while (true)
                    {
                        counter += 2;
                        WIA.CommonDialog common = new WIA.CommonDialog();
                        ImageFile        image  = common.ShowTransfer(dev.Items[1], wiaFormatJPEG, true);
                        if (counter < 10)
                        {
                            pfad = Hauptfenster.tempo_pfad + @"\0" + counter.ToString() + ".jpg";
                        }
                        else
                        {
                            pfad = Hauptfenster.tempo_pfad + @"\" + counter.ToString() + ".jpg";
                        }
                        Byte[]               imageBytes = (byte[])image.FileData.get_BinaryData();
                        MemoryStream         ms         = new MemoryStream(imageBytes);
                        System.Drawing.Image img        = System.Drawing.Image.FromStream(ms);
                        JpegBildKomprimieren(img, int.Parse(textBox1.Text), pfad);
                        //image.SaveFile(pfad); !
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Scannen abgeschlossen");
                }
                #region Alt_Dup
                if (MessageBox.Show("Rückseite eingelegt?", "Duplex", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    dt.Properties["6147"].set_Value(300);
                    dt.Properties["6148"].set_Value(300);
                    try
                    {
                        int counter2 = counter + 1;
                        while (true)
                        {
                            counter2 -= 2;
                            WIA.CommonDialog common = new WIA.CommonDialog();
                            ImageFile        image  = common.ShowTransfer(dev.Items[1], wiaFormatJPEG, true);
                            if (counter2 < 10)
                            {
                                pfad = Hauptfenster.tempo_pfad + @"\0" + counter2.ToString() + ".jpg";
                            }
                            else
                            {
                                pfad = Hauptfenster.tempo_pfad + @"\" + counter2.ToString() + ".jpg";
                            }
                            Byte[]               imageBytes = (byte[])image.FileData.get_BinaryData();
                            MemoryStream         ms         = new MemoryStream(imageBytes);
                            System.Drawing.Image img        = System.Drawing.Image.FromStream(ms);
                            JpegBildKomprimieren(img, int.Parse(textBox1.Text), pfad);
                            //image.SaveFile(pfad);
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Scannen abgeschlossen");
                    }
                }
                else
                {
                    string[] a = System.IO.Directory.GetFiles(Hauptfenster.tempo_pfad);
                    for (int i = 0; i < a.Length; i++)
                    {
                        try
                        {
                            System.IO.File.Delete(a[i]);
                        }
                        catch (Exception)
                        {
                        }
                    }
                    this.Close();
                }

                #endregion
                btn_erstellen.Enabled = true;
            }
            #region lustiger toter Code
            //try
            //{
            //WIA.CommonDialog wcd = new WIA.CommonDialog();
            //Device d = wcd.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);
            //int c = 0;
            //pfad = Hauptfenster.tempo_pfad + @"\" + tbx_name.Text + c.ToString() + ".jpg";
            //while (true)
            //{
            //    WIA.ImageFile img = new ImageFile();
            //    WIA.CommonDialog WiaCommonDialog = new WIA.CommonDialog();
            //    WIA.Item Item = d.Items[1] as WIA.Item;
            //    img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, wiaFormatJPEG, false);
            //    c++;
            //    pfad = Hauptfenster.tempo_pfad + @"\" + tbx_name.Text + c.ToString() + ".jpg";
            //    MessageBox.Show(pfad);
            //    img.SaveFile(pfad);

            //}
            //btn_erstellen.Enabled = true;
            //}
            //catch (Exception)
            //{
            //    MessageBox.Show("Es konnte keine Verbindung zum Scanner hergestellt werden!");
            //    btn_erstellen.Enabled = true;
            //}
            //try
            //{
            //    int c = 0;
            //    const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
            //    WIA.CommonDialog wiaDiag = new WIA.CommonDialog();
            //    WIA.ImageFile wiaImage = null;
            //    while (true)
            //    {
            //        wiaImage = wiaDiag.ShowAcquireImage(
            //        WiaDeviceType.ScannerDeviceType,
            //        WiaImageIntent.GrayscaleIntent,
            //        WiaImageBias.MaximizeQuality,
            //        wiaFormatJPEG, true, true, false);

            //        WIA.Vector vector = wiaImage.FileData;
            //        Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData()));
            //        c++;
            //        pfad = Hauptfenster.tempo_pfad + @"\" + tbx_name.Text + c.ToString() + ".jpg";
            //        i.Save(pfad);
            //    }
            //}
            //catch (Exception)
            //{

            //  btn_erstellen.Enabled = true;
            //}
            #endregion
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Use scanner to scan an image (with user selecting the scanner from a dialog).
        /// </summary>
        /// <returns>Scanned images.</returns>
        public NumerisationWIA()
        {
            WIA.ICommonDialog dialog = new WIA.CommonDialog();
            WIA.Device device = null;
            try {
                device = dialog.ShowSelectDevice
                    (WIA.WiaDeviceType.UnspecifiedDeviceType, true, false);
            }catch(Exception e)
            {
                Console.WriteLine(e);
                Console.WriteLine("Problème lors de la communication avec le scanner : vérifiez les branchements, que le scanner est allumé et réessayez");
                throw new Exception();
            }

            if (device != null)
            {
                this.deviceID = device.DeviceID;
                this.ready = true;
            }
        }
Ejemplo n.º 19
0
        public string scanv2()
        {
            string rutaImagen    = "";
            string nombreAdjunto = "";

            System.Drawing.Image i = null;
            try
            {
                device = dialogo.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);
                ImageFile imageFile = dialogo.ShowAcquireImage(device.Type,
                                                               WiaImageIntent.GrayscaleIntent,
                                                               WiaImageBias.MinimizeSize,
                                                               "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}", false, false, false);
                WIA.Vector vector = imageFile.FileData;

                DateTime fecha = DateTime.Now;
                nombreAdjunto = "scan_" + fecha.Day.ToString()
                                + fecha.Month.ToString()
                                + fecha.Year.ToString()
                                + "_" + fecha.Hour.ToString()
                                + fecha.Minute.ToString()
                                + fecha.Second.ToString()
                                + fecha.Millisecond.ToString()
                                + ".jpeg";
                rutaImagen = ClsGlobals.rutaAdjuntos + nombreAdjunto;


                if (System.IO.File.Exists(rutaImagen))
                {
                    System.IO.File.Delete(rutaImagen);
                }
                try
                {
                    // Se crea el directorio si no existe para almacenar los adjunntos
                    if (Directory.Exists(ClsGlobals.rutaAdjuntos))
                    {
                        DirectoryInfo di = Directory.CreateDirectory(ClsGlobals.rutaAdjuntos);
                    }
                    imageFile.SaveFile(rutaImagen);
                }
                catch (Exception ex)
                {
                    ClsHelper.erroLog(ex);
                }
                i = System.Drawing.Image.FromStream(new
                                                    System.IO.MemoryStream((byte[])vector.get_BinaryData()));
            }
            catch (COMException ex)
            {
                if (ex.ErrorCode == -2145320939)
                {
                    ClsHelper.MensajeSistema("No se encontro dispositivo conectado...");
                }
                else
                {
                    ClsHelper.erroLog(ex);
                }
            }
            catch (Exception)
            {
                ClsHelper.MensajeSistema("No se completo la operación...");
            }
            return(nombreAdjunto);
        }
Ejemplo n.º 20
0
        private void scanButton_Click(object sender, RoutedEventArgs e)
        {
            //filePath = namefile();
            filePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(),"RESUME_SCANNER_image.tif");
            System.IO.File.Delete(filePath);

            dialog = new WIA.CommonDialog();

            try
            {
                scanner = dialog.ShowSelectDevice(
              WiaDeviceType.ScannerDeviceType, false, false);
            }
            catch (Exception msg)
            {
                //Uri uri = new Uri("Images/scanned.tif", UriKind.Relative);
                Uri uri = new Uri("Images/nnenna_u_resume.tif", UriKind.Relative);
                var stream = Application.GetResourceStream(uri).Stream;
                using (FileStream fileStream = System.IO.File.Create(filePath, (int)stream.Length))
                {
                    // Fill the bytes[] array with the stream data
                    byte[] bytesInStream = new byte[stream.Length];
                    stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

                    // Use FileStream object to write to the specified file
                    fileStream.Write(bytesInStream, 0, bytesInStream.Length);
                }
            }

            if (scanner!=null)
            {
                foreach (Property item in scanner.Items[1].Properties)
                {
                    switch (item.PropertyID)
                    {
                        case 6146: //4 is Black-white,gray is 2, color 1
                            SetProperty(item, 4);
                            break;
                        case 6147: //dots per inch/horizontal
                            SetProperty(item, 300);
                            break;
                        case 6148: //dots per inch/vertical
                            SetProperty(item, 300);
                            break;
                        case 6149: //x point where to start scan
                            SetProperty(item, 0);
                            break;
                        case 6150: //y-point where to start scan
                            SetProperty(item, 0);
                            break;
                        case 3096: //Pages
                            SetProperty(item, 1);
                            break;
                        case 3097: //PageSize
                            SetProperty(item, 1);
                            break;
                        case 6151: //horizontal exent
                            SetProperty(item, (int)(8.5 * 300));
                            break;
                        case 6152: //vertical extent
                            SetProperty(item, (int)(11 * 300));
                            break;
                        case 4103: //DataType
                            SetProperty(item, 0);
                            break;
                        case 4104: //BitsPerPixel
                            SetProperty(item, 1);
                            break;
                        case 4110: //BitsPerChannel
                            SetProperty(item, 1);
                            break;
                        case 4114: //NumberOfLines
                            SetProperty(item, 3300);
                            break;
                        case 4116: //ItemSize
                            SetProperty(item, 1056062);
                            break;
                        case 4113: //Bytes Per Line
                            SetProperty(item, 320);
                            break;
                    }
                }

                dialog.ShowSelectItems(scanner);

                ImageFile image = null;
                try
                {
                    image = dialog.ShowTransfer(scanner.Items[1], FormatID.wiaFormatTIFF, false) as ImageFile;
                }
                catch (Exception msg)
                {

                    if (msg.Message.Contains("HRESULT"))
                        MessageBox.Show("Please insert paper into scanner and try again.");
                    return;

                }
                //System.IO.File.Delete(filePath);

                image.SaveFile(filePath);
            }

            BitmapImage _image = new BitmapImage();
            _image.BeginInit();
            _image.CacheOption = BitmapCacheOption.None;
            _image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
            _image.CacheOption = BitmapCacheOption.OnLoad;
            _image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            _image.UriSource = new Uri(filePath, UriKind.RelativeOrAbsolute);
            _image.EndInit();
            scannedImageHolder.Source = _image;
        }
Ejemplo n.º 21
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            try
            {
                // create a new WIA common dialog box for the user to select a device from
                WIA.CommonDialog dlg = new WIA.CommonDialog();
                // show user the WIA device dialog
                Device d = dlg.ShowSelectDevice(WiaDeviceType.CameraDeviceType, true, false);
                // check if a device was selected
                if (d != null)
                {
                    // Print camera properties
                    richTextBox1.AppendText("\n\n Print properties:\n");
                    foreach (Property p in d.Properties)
                    {
                        richTextBox1.AppendText(p.Name + ": " + p.get_Value() + "  (" + p.PropertyID + ":" + p.IsReadOnly + ") \n");
                        // Update UI
                        if (p.PropertyID == 3)
                        {
                            _label = (String)p.get_Value();
                        }
                        if (p.PropertyID == 4)
                        {
                            _label = _label + " - " + p.get_Value();
                        }
                        this.label1.Text = _label;
                    }
                    // Print commands
                    richTextBox1.AppendText("\n\n Print commands:\n");
                    foreach (DeviceCommand dvc in d.Commands)
                    {
                        richTextBox1.AppendText(dvc.Name + ": " + dvc.Description + "  (" + dvc.CommandID + ") \n");
                    }
                    // Print events
                    richTextBox1.AppendText("\n\n Print events:\n");
                    foreach (DeviceEvent dve in d.Events)
                    {
                        richTextBox1.AppendText(dve.Name + ": " + dve.Description + "  (" + dve.Type + ") \n");
                    }
                    // Print item properties
                    richTextBox1.AppendText("\n\n Print item properties:\n");
                    foreach (Property item in d.Items[1].Properties)
                    {
                        richTextBox1.AppendText(item.IsReadOnly + ": " + item.Name + "  (" + item.PropertyID + ") \n");
                    }

                    foreach (WIA.Property p in d.Properties)
                    {
                        Object tempNewProperty;
                        // change Exposure Compensation: value 0 to 2 (ID 2053, isReadonly False)
                        if (p.PropertyID == 2053)
                        {
                            tempNewProperty = (int)-2000; // can not be set to minus values, why???
                            ((IProperty)p).set_Value(ref tempNewProperty);
                            richTextBox1.AppendText(">>>>" + p.get_Value());
                        }
                    }

                    // Now let's take a picture !
                    d.ExecuteCommand(CommandID.wiaCommandTakePicture);
                    richTextBox1.AppendText(".");
                }
                else
                {
                    d = null;
                    richTextBox1.AppendText("Result: no device selected or device could not be read. ");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "WIA Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 22
0
        private string GetDefaultDeviceID()
        {
            string deviceId = Properties.Settings.Default.ScannerDeviceID;
            if (String.IsNullOrEmpty(deviceId))
            {
                // Select a scanner
                WIA.CommonDialog wiaDiag = new WIA.CommonDialog();
                Device d = wiaDiag.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);
                if (d != null)
                {
                    deviceId = d.DeviceID;
                    Properties.Settings.Default.ScannerDeviceID = deviceId;
                    Properties.Settings.Default.Save();
                }

                // Register for the scanner button event
                //string eventId = "";
                //DeviceManager manager = new DeviceManager();
                //string command = String.Format("{0} {1}", Application.ExecutablePath, "/StiDevice:%1");
                //string description = "Converts scanned documents to PDF and uploads to Evernote";
                //string icon = String.Format("{0},0", Application.ExecutablePath);
                //// Affects registry keys
                //// HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\StillImage\Events\EVENT_ID
                //// HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Control\StillImage\Events\EVENT_ID
                //// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StillImage\Events\EVENT_ID
                //manager.RegisterPersistentEvent(command, "ScanToEvernote", description, icon, eventId, deviceId);
            }

            return deviceId;
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Use scanner to scan an image (with user selecting the scanner from a dialog).
 /// </summary>
 /// <returns>Scanned images.</returns>
 public static List<System.Drawing.Image> AutoScan(IItem scannnerItem, int scanResolutionDPI, double scanStartLeftPixel, double scanStartTopPixel,
             double scanWidthPixels, double scanHeightPixels, int brightnessPercents, int contrastPercents, int colorMode)
 {
     WIA.ICommonDialog dialog = new WIA.CommonDialog();
     WIA.Device device = dialog.ShowSelectDevice(WIA.WiaDeviceType.UnspecifiedDeviceType, true, false);
     if (device != null)
     {
         return AutoScan(device.DeviceID, scanResolutionDPI, scanStartLeftPixel, scanStartTopPixel,
             scanWidthPixels, scanHeightPixels, brightnessPercents, contrastPercents, colorMode);
     }
     else
     {
         throw new Exception("You must select a device for scanning.");
     }
 }
Ejemplo n.º 24
0
        void Scan(string directory, ScanColor clr, int dpi)
        {
            string deviceid;

            //Choose Scanner
            WIA.CommonDialog class1 = new WIA.CommonDialog();
            Device           d      = class1.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false);

            if (d != null)
            {
                deviceid = d.DeviceID;
            }
            else
            {
                //no scanner chosen
                return;
            }
            WIA.CommonDialog WiaCommonDialog = new WIA.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);
                const string wiaFormatJPEG    = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
                string       varImageFileName = "";
                try
                {//WATCH OUT THE FORMAT HERE DOES NOT MAKE A DIFFERENCE... .net will load it as a BITMAP!
                    img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, wiaFormatJPEG, false);
                    //process image:
                    //Save to file and open as .net IMAGE
                    //string varImageFileName = Path.GetTempFileName();
                    varImageFileName = directory + numPages.ToString() + ".jpg";
                    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)
                {
                    MessageBox.Show("Beim Scannen ist ein Fehler aufgetreten!");
                }
                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
                    WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER.ToString();
                    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++;
                }
                WiaDev = null;
            }
            EventHandler tempCom = ScanComplete;

            if (tempCom != null)
            {
                tempCom(this, EventArgs.Empty);
            }
        }
        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 = "";
            }
        }
Ejemplo n.º 26
0
        public string GetTestInfo()
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                // create a new WIA common dialog box for the user to select a device from
                CommonDialog dlg = new CommonDialog();

                // show user the WIA device dialog
                Device d = dlg.ShowSelectDevice(WiaDeviceType.CameraDeviceType, true, false);

                // check if a device was selected
                if (d != null)
                {
                    // Print camera properties
                    sb.Append("\n\n Print properties:\n");
                    foreach (Property p in d.Properties)
                    {
                        sb.Append(p.Name + ": " + p.get_Value() + "  (" + p.PropertyID + ":" + p.IsReadOnly + ") \n");

                        // Update UI
                        if (p.PropertyID == 3) sb.Append("prop 3 - " + (String)p.get_Value());
                        if (p.PropertyID == 4) sb.Append("prop 4 - " + (String)p.get_Value());

                    }

                    // Print commands
                    sb.Append("\n\n Print commands:\n");
                    foreach (DeviceCommand dvc in d.Commands)
                    {
                        sb.Append(dvc.Name + ": " + dvc.Description + "  (" + dvc.CommandID + ") \n");
                    }

                    // Print events
                    sb.Append("\n\n Print events:\n");
                    foreach (DeviceEvent dve in d.Events)
                    {
                        sb.Append(dve.Name + ": " + dve.Description + "  (" + dve.Type + ") \n");
                    }

                    // Print item properties
                    sb.Append("\n\n Print item properties:\n");
                    foreach (Property item in d.Items[1].Properties)
                    {
                        sb.Append(item.IsReadOnly + ": " + item.Name + "  (" + item.PropertyID + ") \n");
                    }

                    foreach (Property p in d.Properties)
                    {
                        Object tempNewProperty;

                        // change Exposure Compensation: value 0 to 2 (ID 2053, isReadonly False)
                        if (p.PropertyID == 2053)
                        {
                            tempNewProperty = (int)-2000;  // can not be set to minus values, why???
                            ((IProperty)p).set_Value(ref tempNewProperty);
                            sb.Append(">>>>" + p.get_Value());
                        }
                    }

                    // Now let's take a picture !
                    d.ExecuteCommand(CommandID.wiaCommandTakePicture);
                    sb.Append(".");

                }
                else
                {
                    sb.Append("Result: no device selected or device could not be read. ");
                }

                return sb.ToString();
            }
            catch (Exception ex)
            {
                return "Камера не подключена";
            }
        }