private void SetWIAProperty(WIA.IProperties properties, object propName, object propValue) { WIA.Property prop = properties.get_Item(ref propName); try { prop.set_Value(ref propValue); } catch (Exception) { } }
/// <summary> /// /// </summary> /// <param name="properties"></param> /// <param name="nomePropriedade"></param> /// <param name="valorPropriedade"></param> private static void GravaPropriedadeWIA(WIA.IProperties propriedades, object nomePropriedade, object valorPropriedade) { try { WIA.Property prop = propriedades.get_Item(ref nomePropriedade); prop.set_Value(ref valorPropriedade); } catch (Exception mEx) { Mensagens.Add(string.Format("Não foi possível alterar a propriedade {0} Para {1}, description: {2}", nomePropriedade.ToString(), valorPropriedade.ToString(), DescricaoErro(mEx))); } }
private static void SetWIAProperty(WIA.IProperties properties, object propName, object propValue) { WIA.Property prop = properties.get_Item(ref propName); prop.set_Value(ref propValue); }
/// <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); }
private void setItem(IItem item, object property, object value) { WIA.Property aProperty = item.Properties.get_Item(ref property); aProperty.set_Value(ref value); }
public Task <bool> Scann(PdfViewer obj = null) { scannedDoc = new List <string>(); PDFViewer = obj; Application.Current.Dispatcher.Invoke((System.Action)(delegate { obj.Visibility = Visibility.Collapsed; })); StaticSourcesViewModel.ShowMensajeProgreso("Espere Por Favor, Escaneando..."); try { var morePages = true; var commonDialogClass = new CommonDialog(); var scannerDevice = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false); var pagecount = 0; if (scannerDevice != null) { scannerDevice.Properties["Pages"].set_Value(1); scannerDevice.Properties["Document Handling Select"].set_Value(1); var document = new PdfDocument(); while (morePages) { try { var scannnerItem = scannerDevice.Items[1]; AdjustScannerSettings(scannnerItem, 150, 0, 0, 1250, 1700, 0, 0, WiaImageIntent.ColorIntent); var img = (ImageFile)scannnerItem.Transfer("{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}"); if (img != null) { document.Pages.Add(new PdfPage()); var xgr = XGraphics.FromPdfPage(document.Pages[pagecount]); var Ximg = XImage.FromBitmapSource(ConvertScannedImage(img)); xgr.DrawImage(Ximg, 0, 0, 595, 842); pagecount++; } WIA.Property documentHandlingSelect = null; WIA.Property documentHandlingStatus = null; foreach (WIA.Property prop in scannerDevice.Properties) { if (prop.PropertyID == 3088) { documentHandlingSelect = prop; } if (prop.PropertyID == 3087) { documentHandlingStatus = prop; } } morePages = false; if (documentHandlingSelect != null) { if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & 0x00000001) != 0) { morePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & 0x00000001) != 0); } } } catch (Exception ex) { if (pagecount <= 0) { Application.Current.Dispatcher.Invoke((System.Action)(delegate { if (ex.Message == "Exception from HRESULT: 0x80210003") { StaticSourcesViewModel.Mensaje("Digitalización", "Revise que la bandeja tenga hojas", StaticSourcesViewModel.enumTipoMensaje.MENSAJE_INFORMACION); } else if (ex.Message == "Value does not fall within the expected range.") { StaticSourcesViewModel.Mensaje("Digitalización", "*- Revise que el escáner este encendido.\n*- Revise que el escáner este bien conectado", StaticSourcesViewModel.enumTipoMensaje.MENSAJE_INFORMACION); } else { StaticSourcesViewModel.Mensaje("Digitalización", "Hay problemas para conectarse con el escaner", StaticSourcesViewModel.enumTipoMensaje.MENSAJE_INFORMACION); } })); } morePages = false; } } if (pagecount > 0) { fileNamepdf = Path.GetTempPath() + Path.GetRandomFileName().Split('.')[0] + ".pdf"; document.Save(fileNamepdf); ScannedDocument = File.ReadAllBytes(fileNamepdf); Application.Current.Dispatcher.Invoke((System.Action)(delegate { obj.LoadFile(fileNamepdf); obj.Visibility = Visibility.Visible; })); } } } catch (Exception ex) { Application.Current.Dispatcher.Invoke((System.Action)(delegate { if (ex.Message.Contains("HRESULT: 0x80210015")) { StaticSourcesViewModel.Mensaje("Digitalización", "*- No tienes ningun escaner instalado.\n*- Revise que el escáner este encendido.\n*- Revise que el escáner este bien conectado", StaticSourcesViewModel.enumTipoMensaje.MENSAJE_INFORMACION); } if (ex.Message.Contains("HRESULT: 0x80070021")) { StaticSourcesViewModel.Mensaje("Digitalización", "Hay problemas para conectarse con el escaner", StaticSourcesViewModel.enumTipoMensaje.MENSAJE_INFORMACION); } })); } StaticSourcesViewModel.CloseMensajeProgreso(); return(TaskEx.FromResult(true)); }
/// <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); }
/// <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); } }
/// <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); }
/// <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; } } } }
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); }
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; } } }
/// <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); }
/// <summary> /// /// </summary> /// <param name="scannerId"></param> /// <param name="qualidade"></param> /// <param name="tamanho"></param> /// <param name="tipo"></param> /// <returns></returns> private static List <KeyValuePair <string, Image> > DigitalizaItensEspecifico(string scannerId, WIAScanQuality qualidade, WIAPageSize tamanho, TipoLeituraDocumento tipo) { List <KeyValuePair <string, Image> > images = new List <KeyValuePair <string, Image> >(); //Dictionary<string,Image> images = new Dictionary<string,Image>(); bool hasMorePages = true; WIA.Item item; Mensagens = new HashSet <string>(); // 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) { device = info.Connect(); //AcquireNormal(device); Dispositivos[scannerId].Propriedades.Clear(); CarregaPropriedades(device, Dispositivos[scannerId].Propriedades); 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 Mensagens.Add("Não foi possível conectar-se ao o dispositivo especificado\n" + availableDevices); } ConfiguraTipoScan(ref device, tipo); item = device.Items[1] as WIA.Item; AjustaPropriedadesDispositivo(item, 0, 0, 0, 0, 1, qualidade, tamanho); WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog(); while (hasMorePages) { try { //Some scanner need WIA_DPS_PAGES to be set to 1, otherwise all pages are acquired but only one is returned as ImageFile GravaPropriedade(ref device, DEVICE_PROPERTY_PAGES_ID, 1); //Scan image WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, WIA.FormatID.wiaFormatPNG, false); if (image != null) { // save to file string fileName = SalvarPNG(image); images.Add(new KeyValuePair <string, Image>(fileName, Image.FromFile(fileName))); } //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); } } } catch (Exception exc) { int error = CodigoErroWIA(exc); Mensagens.Add(DescricaoErro(exc)); if (error == WIA_ERROR_PAPER_EMPTY) { hasMorePages = false; } if (error == 0) { throw exc; } } } device = null; return(images); }
/// <summary> /// /// </summary> /// <param name="scannerId"></param> /// <param name="qualidade"></param> /// <param name="tamanho"></param> /// <param name="tipo"></param> /// <returns></returns> private static List <KeyValuePair <string, Image> > DigitalizaItens(string scannerId, WIAScanQuality qualidade, WIAPageSize tamanho, TipoLeituraDocumento tipo) { List <KeyValuePair <string, Image> > images = new List <KeyValuePair <string, Image> >(); //Dictionary<string,Image> images = new Dictionary<string,Image>(); bool hasMorePages = true; WIA.Item item; Mensagens = new HashSet <string>(); while (hasMorePages) { // select the correct scanner using the provided scannerId parameter WIA.Device device = LocalizaDispositio(scannerId); try { //SetWIAProperty(device.Properties, WIA_DEVICE_PROPERTY_PAGES_ID, 1); //Escolha da forma de scaneamento, Feeder ou Flatbad ConfiguraTipoScan(ref device, tipo); item = device.Items[1] as WIA.Item; AjustaPropriedadesDispositivo(item, 0, 0, 0, 0, 1, qualidade, tamanho); // scan image WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog(); WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, WIA.FormatID.wiaFormatPNG, false); if (image != null) { // save to file string fileName = SalvarPNG(image); images.Add(new KeyValuePair <string, Image>(fileName, Image.FromFile(fileName))); } //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); } } } catch (Exception exc) { int error = CodigoErroWIA(exc); Mensagens.Add(DescricaoErro(exc)); if (error == WIA_ERROR_PAPER_EMPTY) { hasMorePages = false; } if (error == 0) { throw exc; } } finally { item = null; } } return(images); }