public WiaDataSource(WIA.DeviceInfo info)
 {
   fIdent = info;
   fDevice = null;
   fItem = null;
   fCommonDialog = null;
 }
        private void GetScannerAsync(Action completionHandler)
        {
            if (device == null)
            {
                Task task = new Task(new Action(() =>
                {
                    if (globalDialog == null)
                    {
                        globalDialog = new WIA.CommonDialog();
                    }
                    try
                    {
                        device = globalDialog.ShowSelectDevice(DeviceType: WIA.WiaDeviceType.ScannerDeviceType, AlwaysSelectDevice: true);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }
                }));

                task.Start();
                Task.WaitAll(task);
            }
            completionHandler();
        }
Exemple #3
0
        private void BotonCapturarImagen_Click(object sender, EventArgs e)
        {
            try {
                var           WiaDialog = new WIA.CommonDialog();
                WIA.ImageFile WiaImage  = null;

                WiaImage = WiaDialog.ShowAcquireImage(
                    WIA.WiaDeviceType.UnspecifiedDeviceType,
                    WIA.WiaImageIntent.ColorIntent,
                    WIA.WiaImageBias.MaximizeQuality,
                    System.Drawing.Imaging.ImageFormat.Jpeg.Guid.ToString("B"), true, false, false);

                if (WiaImage != null)
                {
                    var vector = WiaImage.FileData;
                    using (var Recorte = new Entrada.AuxForms.ImagenRecorte()) {
                        Recorte.Imagen = System.Drawing.Image.FromStream(new System.IO.MemoryStream((byte[])vector.get_BinaryData()));
                        if (Recorte.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            EntradaImagen.Image = Recorte.Imagen;
                            this.Changed        = true;
                            this.ActualizarElemento();
                        }
                    }
                }
            } catch (Exception ex) {
                Lui.Forms.MessageBox.Show("No se puede conectar con el dispositivo de captura. " + ex.Message, "Error");
            }
        }
        public bool SelectDevice()
        {
            WIA.CommonDialog dialog = new WIA.CommonDialog();
            WIA.Device       device = dialog.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, true, false);

            SelectedDevice = device;

            return(SelectedDevice != null);
        }
 private void Close()
 {
   if(IsOpen)
   {
     fDevice = null;
     fItem = null;
     fCommonDialog = null;
   }
 }
 private bool Open()
 {
   if(IsOpen == false)
   {
     fDevice = fIdent.Connect();
     fItem = fDevice.Items[1] as WIA.Item;
     fCommonDialog = new WIA.CommonDialog();
   }
   return IsOpen;
 }
 /// <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.");
     }
 }
 /// <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("Tarama için bir cihaz seçiniz");
     }
 }
Exemple #9
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.");
     }
 }
Exemple #10
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("Você precisa selecionar um disposito para scanner.");
     }
 }
Exemple #11
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("Escolha um scanner para iniciar");
     }
 }
Exemple #12
0
        private void GetScannerAsync(Action completionHandler)
        {
            if (device == null)
            {
                Task task = new Task(new Action(() =>
                {
                    if (globalDialog == null)
                    {
                        globalDialog = new WIA.CommonDialog();
                    }
                    device = globalDialog.ShowSelectDevice(DeviceType: WIA.WiaDeviceType.ScannerDeviceType, AlwaysSelectDevice: true);
                }));

                task.Start();
                Task.WaitAll(task);
            }
            completionHandler();
        }
Exemple #13
0
        public static WiaDevice ShowSelectionDialog()
        {
            var dialog = new WIA.CommonDialog();

            try
            {
                var d = dialog.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, true);
                if (d != null)
                    return new WiaDevice(d);
            }
            catch (COMException e)
            {
                switch ((WiaConstant)e.ErrorCode)
                {
                    case WiaConstant.WIA_S_NO_DEVICE_AVAILABLE:
                        throw new Exceptions.WiaNoDeviceAvailableException(e);

                    default:
                        throw new Exceptions.WiaException("Error selecting device", (WiaConstant)e.ErrorCode, e);
                }
            }

            return null;
        }
Exemple #14
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;
                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;
        }
Exemple #15
0
        private void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                // parametros de scanner
                int resolucion  = 150;
                int anchoImagen = 1200;
                int altoImagen  = 1500;
                int modoColor   = 1;

                // la mas importante
                bool HayMasPaginas = true; // tiene mas paginas :)

                // ruta principal donde se guardan los archivos
                string rutaBase = string.Format("{0}\\{1}", Application.StartupPath, DateTime.Now.ToString("yyyMMddhhmmss"));

                Directory.CreateDirectory(rutaBase);

                // elegir escanner
                WIA.CommonDialog dialogoSeleccionaEscanner = new WIA.CommonDialog();
                WIA.Device       escaner = dialogoSeleccionaEscanner.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, true, false);

                if (escaner != null)
                {
                    idEscaner = escaner.DeviceID;
                }
                else
                {
                    MessageBox.Show("No se eligió Escaner");
                    return;
                }

                int x             = 0;
                int numeroPaginas = 0;

                while (HayMasPaginas)
                {
                    // mientras la bandera de mas paginas este activa
                    // conectar escaner
                    // mostrando avance de escaneo
                    WIA.CommonDialog  dialogoEscaneo = new WIA.CommonDialogClass();
                    WIA.DeviceManager manager        = new WIA.DeviceManagerClass();
                    WIA.Device        dispoWIA       = null;

                    // cargando el dispositivo
                    foreach (WIA.DeviceInfo scannerInfo in manager.DeviceInfos)
                    {
                        if (scannerInfo.DeviceID == idEscaner)
                        {
                            WIA.Properties infoprop = null;
                            infoprop = scannerInfo.Properties;

                            dispoWIA = scannerInfo.Connect();

                            break;
                        }
                    }

                    // inicia escaneo
                    WIA.ImageFile imgEscaneo  = null;
                    WIA.Item      escanerItem = dispoWIA.Items[1] as WIA.Item;

                    AdjustScannerSettings(escanerItem, resolucion, 0, 0, anchoImagen, altoImagen, 0, 0, modoColor);

                    // tomando la imagen
                    imgEscaneo = (WIA.ImageFile)dialogoEscaneo.ShowTransfer(escanerItem, WIA.FormatID.wiaFormatPNG, false);

                    string RutaNombreEscaneo = String.Format("{0}\\{1}.png", rutaBase, x.ToString());

                    if (File.Exists(RutaNombreEscaneo))
                    {
                        //file exists, delete it
                        File.Delete(RutaNombreEscaneo);
                    }

                    imgEscaneo.SaveFile(RutaNombreEscaneo);
                    numeroPaginas++;
                    x++;
                    imgEscaneo = null;

                    // preguntar si hay mas documentos pendientes de escaneo
                    if (MessageBox.Show("¿Deseas escanear otro documento?. Antes de seleccionar 'Yes' Por favor introduzca el documento a escanear.", "Escaner", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    {
                        HayMasPaginas = false;
                    }
                }

                // una vez escaneado los dosucmentos, se hace un pdf con ellos para despues hacerlo zip
                // rutaBase es el nombre de la variable de la carpeta
                MessageBox.Show("Escaneo finalizado. Armando archivo pdf");
                string nombreArchivoPdf = string.Format("{0}\\{1}.pdf", rutaBase, DateTime.Now.ToString("yyyMMddhhmmss"));

                Document  pdfDoc = new Document(PageSize.LETTER, 2, 2, 2, 2);
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(nombreArchivoPdf, FileMode.CreateNew));

                pdfDoc.Open();

                // tomar las imagenes del escaneo
                for (int i = 0; i < x; i++)
                {
                    // tomar la imagen
                    string rutaImagen = String.Format("{0}\\{1}.png", rutaBase, i.ToString());

                    PdfContentByte cb = writer.DirectContent;

                    using (FileStream fsSource = new FileStream(rutaImagen, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        Image img = Image.GetInstance(fsSource);
                        img.ScaleToFit(pdfDoc.PageSize.Width, pdfDoc.PageSize.Height);
                        pdfDoc.Add(img);
                    }
                }

                pdfDoc.Close();

                MessageBox.Show("Archivo pdf generado. Generando archivo zip");

                // comprimir
                FileInfo        pdfFileInfo      = new FileInfo(nombreArchivoPdf);
                string          nombreArchivoZip = string.Format("{0}\\{1}.zip", rutaBase, DateTime.Now.ToString("yyyMMddhhmmss"));
                ZipOutputStream zipStream        = new ZipOutputStream(File.Create(nombreArchivoZip));
                zipStream.SetLevel(6);

                // abrir el archivo para escribirlo
                FileStream pdfFile = File.OpenRead(nombreArchivoPdf);
                byte[]     buffer  = new byte[pdfFile.Length];
                pdfFile.Read(buffer, 0, buffer.Length);

                // agregando el archivo a la carpeta comprimida
                ZipEntry entry = new ZipEntry(Path.GetFileName(nombreArchivoPdf))
                {
                    DateTime = pdfFileInfo.LastWriteTime,
                    Size     = pdfFile.Length
                };

                pdfFile.Close();

                Crc32 objCrc32 = new Crc32();
                objCrc32.Reset();
                objCrc32.Update(buffer);

                entry.Crc = objCrc32.Value;
                zipStream.PutNextEntry(entry);
                zipStream.Write(buffer, 0, buffer.Length);

                zipStream.Finish();
                zipStream.Close();

                MessageBox.Show("Archivo zip generado. Enviando archivo por FTP");

                // enviar el documento en ftp

                MessageBox.Show("proceso completo.");
            }
            catch (Exception ex)
            {
                // cachando errores com
                if (ex is COMException)
                {
                    // Convert the error code to UINT
                    uint errorCode = (uint)((COMException)ex).ErrorCode;

                    // See the error codes
                    if (errorCode == 0x80210006)
                    {
                        MessageBox.Show("The scanner is busy or isn't ready");
                    }
                    else if (errorCode == 0x80210064)
                    {
                        MessageBox.Show("The scanning process has been cancelled.");
                    }
                    else if (errorCode == 0x8021000C)
                    {
                        MessageBox.Show("There is an incorrect setting on the WIA device.");
                    }
                    else if (errorCode == 0x80210005)
                    {
                        MessageBox.Show("The device is offline. Make sure the device is powered on and connected to the PC.");
                    }
                    else if (errorCode == 0x80210001)
                    {
                        MessageBox.Show("An unknown error has occurred with the WIA device.");
                    }
                }
                else
                {
                    MessageBox.Show("Error " + ex.Message);
                }
            }
        }
        public void Scan(WiaDocumentHandlingType handlingType      = WiaDocumentHandlingType.Feeder,
                         WiaDocumentHandlingType?duplexOrOtherMode = null,
                         List <string> imagesFromScanner           = null)
        {
            if (imagesFromScanner == null)
            {
                imagesFromScanner = new List <string>();
            }
            SelectDevice();

            if (SelectedDevice == null)
            {
                return;
            }


            bool hasMorePages = true;


            // select the correct scanner using the provided scannerId parameter
            WIA.DeviceManager manager = new WIA.DeviceManager();
            WIA.Device        device  = null;
            try
            {
                if (manager.DeviceInfos == null || manager.DeviceInfos.Count < 1)
                {
                    throw new WiaScannerDeviceNotFoundException((string)Application.Current.FindResource("NemaDostupnihSkeneraUzvicnik"));
                }

                foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == SelectedDevice.DeviceID)
                    {
                        // connect to scanner
                        device = info.Connect();
                        break;
                    }
                }

                if (handlingType == WiaDocumentHandlingType.Feeder)
                {
                    if (duplexOrOtherMode != null)
                    {
                        SetProperty(device.Properties, (uint)WiaProperty.DocumentHandlingSelect, (uint)(handlingType | duplexOrOtherMode));
                    }
                    else
                    {
                        SetProperty(device.Properties, (uint)WiaProperty.DocumentHandlingSelect, (uint)handlingType);
                    }
                }
            }
            catch (Exception ex)
            {
                device = null;
            }

            while (hasMorePages)
            {
                // device was not found
                if (device == null)
                {
                    throw new WiaScannerDeviceNotFoundException((string)Application.Current.FindResource("OdabraniSkenerNijeDostupanUzvicnik"));
                }

                WIA.Item item = device.Items[1] as WIA.Item;
                try
                {
                    PreviousPropertyValues.Clear();

                    foreach (var property in PropertyValues)
                    {
                        WIA.Property prop = GetProperty(item.Properties, property.Key);
                        PreviousPropertyValues.Add(property.Key, prop?.get_Value());

                        var supported = prop.SubTypeValues;
                        SetProperty(item.Properties, property.Key, property.Value);
                    }


                    // scan image
                    WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();


                    WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, true);

                    WIA.ImageFile duplexImage = null;
                    if (duplexOrOtherMode == WiaDocumentHandlingType.Duplex)
                    {
                        Thread.Sleep(100);
                        duplexImage = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, true);
                    }
                    // save to temp file
                    string fileName = Path.GetTempFileName();
                    if (image != null)
                    {
                        File.Delete(fileName);
                        image.SaveFile(fileName);
                        Marshal.FinalReleaseComObject(image);
                        image = null;
                        // add file to output list
                        imagesFromScanner.Add(fileName);
                    }
                    if (duplexImage != null)
                    {
                        string duplexFileName = Path.GetTempFileName();
                        File.Delete(duplexFileName);
                        duplexImage.SaveFile(duplexFileName);
                        Marshal.FinalReleaseComObject(duplexImage);
                        duplexImage = null;
                        // add file to output list
                        imagesFromScanner.Add(duplexFileName);
                    }


                    item = null;

                    WIA.Property documentHandlingSelect = null;
                    WIA.Property documentHandlingStatus = null;
                    foreach (WIA.Property prop in device.Properties)
                    {
                        if (prop.PropertyID == (uint)WiaProperty.DocumentHandlingSelect)
                        {
                            documentHandlingSelect = prop;
                        }
                        if (prop.PropertyID == (uint)WiaProperty.DocumentHandlingStatus)
                        {
                            documentHandlingStatus = prop;
                        }
                    }
                    hasMorePages = false;

                    if (documentHandlingSelect != null)
                    {
                        var propId            = documentHandlingSelect.PropertyID;
                        var propValue         = documentHandlingSelect.get_Value();
                        var propValueBitCheck = (propValue & ((uint)WiaDocumentHandlingType.Feeder));
                        if (propValueBitCheck != 0)
                        {
                            var statusId            = documentHandlingStatus.PropertyID;
                            var statusValue         = documentHandlingStatus.get_Value();
                            var statusValueBitCheck = (statusValue & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY);
                            hasMorePages = (statusValueBitCheck != 0);
                        }
                    }


                    //Thread.Sleep(500);
                }
                catch (WiaScannerDeviceNotFoundException exc)
                {
                    throw exc;
                }
                catch (IOException exc)
                {
                    throw exc;
                }
                catch (COMException exc)
                {
                    if (imagesFromScanner?.Count() < 1)
                    {
                        if ((uint)exc.ErrorCode == 0x80210003)
                        {
                            throw new WiaScannerInsertPaperException(exc.Message);
                        }
                        else
                        {
                            throw exc;
                        }
                    }
                    else // U slucaju da su pokupljene slike, kad dodje do poruke o poslednjoj skeniranoj prekidamo izvrsavanje
                    {
                        return;
                    }
                }
                catch (Exception exc)
                {
                    throw exc;
                }
            }
        }
Exemple #17
0
        public static List <Image> Scan(string scannerName)
        {
            List <Image> images       = new List <Image>();
            bool         hasMorePages = true;
            bool         paperEmpty   = false;

            while (hasMorePages)
            {
                Dictionary <string, string> devices = WiaScanner.GetDevices();
                var scannerId             = devices.FirstOrDefault(x => x.Value == scannerName).Key;
                WIA.DeviceManager manager = new WIA.DeviceManager();
                WIA.Device        device  = null;
                // select the correct scanner using the provided scannerId parameter
                foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == scannerId && info.Type == WIA.WiaDeviceType.ScannerDeviceType)
                    {
                        // connect to scanner
                        device = info.Connect();
                        break;
                    }
                }

                // device was not found
                if (device == null)
                {
                    // enumerate available devices
                    string availableDevices = "";
                    foreach (var d in devices)
                    {
                        availableDevices += d.Value + "\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 = SetPaperSetting(device);

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

                    //WIA.ImageProcess imp = new WIA.ImageProcess();  // use to compress jpeg.
                    //imp.Filters.Add(imp.FilterInfos["Convert"].FilterID);
                    ////imp.Filters[1].Properties["FormatID"].set_Value(wiaFormatJPEG);
                    //imp.Filters[1].Properties["FormatID"].set_Value(wiaFormatJPEG);
                    //imp.Filters[1].Properties["Quality"].set_Value(80); // 1 = low quality, 100 = best
                    //image = imp.Apply(image);  // apply the filters

                    // get a tempfile path
                    string fileName = Path.GetTempFileName();
                    // delete any existing file first
                    File.Delete(fileName);
                    // save to temp file
                    image.SaveFile(fileName);
                    // make the original (wia) image null
                    image = null;
                    // get system.drawing image from temporary file and add file to output list
                    images.Add(Image.FromFile(fileName, true));

                    //var imageBytes = (byte[])image.FileData.get_BinaryData();
                    //var stream = new MemoryStream(imageBytes);
                    //images.Add(Image.FromStream(stream));
                }
                catch (System.Runtime.InteropServices.COMException cx)
                {
                    string ex           = string.Empty;
                    int    comErrorCode = GetWIAErrorCode(cx);
                    if (comErrorCode > 0)
                    {
                        ex = GetErrorCodeDescription(comErrorCode);
                    }
                    if (comErrorCode == 3 && images.Count == 0)
                    {
                        throw new Exception(ex);
                    }
                    else if (comErrorCode == 3 && images.Count > 0)
                    {
                        paperEmpty = true;
                    }
                }

                finally
                {
                    item = null;
                    // assume there are no more pages
                    hasMorePages = false;
                    if (!paperEmpty)
                    {
                        //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;
                            }
                        }

                        // 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);
        }
Exemple #18
0
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <returns>Scanned images.</returns>
        public static List<string> Scan( string scannerId, int dpi, int color, int brightness, int contrast )
        {
            if ( scannerId == null )
            {
                throw new DeviceNotFoundException( "er_DeviceMiss" );
            }
            var images = new List<string>();
            bool feeder = false;
            while ( true )
            {
                var device = ConnectDevice( scannerId ) as WIA.Device;

                // can't connect
                if ( device == null )
                {
                    throw new DeviceOfflineException( "er_CantConn" );
                }

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

                Item.Properties[ CurrentIntent ].set_Value( color );
                Item.Properties[ HorizontalResolution ].set_Value( dpi );
                Item.Properties[ VerticalResolution ].set_Value( dpi );

                Item.Properties[ HorizontalExtent ].set_Value( 210 / 25.4 * dpi );
                Item.Properties[ VerticalExtent ].set_Value( 296 / 25.4 * dpi );

                Item.Properties[ Brightness ].set_Value( brightness );
                Item.Properties[ Contrast ].set_Value( contrast );

                try
                {
                    if ( ( feeder == false ) && ( GetDeviceProperty( device, DocumentHandlingSelect ) == WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER ) )
                    {
                        feeder = true;
                    }
                    if ( ( feeder == true ) && ( GetDeviceProperty( device, DocumentHandlingSelect ) == WIA_DPS_DOCUMENT_HANDLING_SELECT.FLATBED ) )
                    {
                        break;
                    }
                }
                catch { }

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

                    var temporary = Path.GetTempFileName();
                    File.Delete( temporary );

                    image.SaveFile( temporary );
                    images.Add( temporary );
                }
                catch ( Exception )
                {
                    throw new UnknownScanException( "er_ScanErr" );
                }

                if ( feeder == false )
                {
                    break;
                }

                if ( GetDeviceProperty( device, DocumentHandlingSelect ) == WIA_DPS_DOCUMENT_HANDLING_SELECT.FLATBED )
                {
                    break;
                }

                if ( GetDeviceProperty( device, DocumentHandlingStatus ) == WIA_DPS_DOCUMENT_HANDLING_STATUS.FLAT_READY )
                {
                    break;
                }
            }
            return images;
        }
    /// <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;

            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);
    }
Exemple #20
0
        /*internal object GetProperty(WiaProperty property)
        {
            return device.Properties.Cast<WIA.Property>().Single(prop => prop.PropertyID == (int)property).get_Value();
        }

        internal void SetProperty(WiaProperty property, object value)
        {
            device.Properties.Cast<WIA.Property>().Single(prop => prop.PropertyID == (int)property).set_Value(value);
        }*/
        public System.Drawing.Image Scan()
        {
            var dialog = new WIA.CommonDialog();

            try
            {
                //do
                {
                    //!!properties[WiaProperty.WIA_IPS_DOCUMENT_HANDLING_SELECT] = 2;

                    var item = (WIA.Item)device.Items[1];

                    var itemProperties = new WiaPropertyMap(item);
                    itemProperties[WiaProperty.WIA_IPA_DATATYPE] = 3;
                    itemProperties[WiaProperty.WIA_IPS_XRES] = 200;
                    itemProperties[WiaProperty.WIA_IPS_YRES] = 200;
                    //new Size(8500, 11000)
                    var pageWidth = 8500 * 200 / 1000;
                    var pageHeight = 11000 * 200 / 1000;
                    var pageMaxWidth = properties.GetValue<int>(WiaProperty.WIA_DPS_HORIZONTAL_BED_SIZE) * 200 / 1000;
                    var pageMaxHeight = properties.GetValue<int>(WiaProperty.WIA_DPS_VERTICAL_BED_SIZE) * 200 / 1000;

                    var horizontalPos = pageMaxWidth - pageWidth;
                    pageWidth = Math.Min(pageWidth, pageMaxWidth);
                    pageHeight = Math.Min(pageHeight, pageMaxHeight);

                    itemProperties[WiaProperty.WIA_IPS_XEXTENT] = pageWidth;
                    itemProperties[WiaProperty.WIA_IPS_YEXTENT] = pageHeight;
                    itemProperties[WiaProperty.WIA_IPS_XPOS] = horizontalPos;

                    /*var img = (WIA.ImageFile)dialog.ShowTransfer(item, WiaImageFormat.WiaImgFmt_BMP.ToString());
                    img.*/
                    var img = (WIA.ImageFile)dialog.ShowTransfer(item, /*WiaImageFormat.WiaImgFmt_BMP.ToString()*/"{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}", false);
                    System.Drawing.Image image;
                    using (var stream = new System.IO.MemoryStream((byte[])img.FileData.get_BinaryData()))
                        image = System.Drawing.Image.FromStream(stream);
                    return image;
                }
            }
            finally
            {
            }
        }