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."); } }
/// <summary> /// Inicia a digitalização dos documentos depositados no dispositivo selecionado /// </summary> /// <param name="scannerId"></param> /// <param name="tamanho"></param> /// <param name="tipoDigitalizacao"></param> /// <returns></returns> public static List <KeyValuePair <string, Image> > Scan(string scannerId, WIAPageSize tamanho, TipoLeituraDocumento tipoDigitalizacao) { WIA.Device device = LocalizaDispositio(scannerId); String description = device.Properties["Name"].get_Value().ToString(); if (description.ToLower().Contains("brother") || description.Contains("Canon MF4500")) { return(DigitalizaItensEspecifico(scannerId, WIAScanQuality.Final, tamanho, tipoDigitalizacao)); } else { return(DigitalizaItens(scannerId, WIAScanQuality.Final, tamanho, tipoDigitalizacao)); } }
/// <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); }
/// <summary> /// /// </summary> /// <param name="item"></param> /// <param name="resolucaoDPI"></param> /// <param name="pixelInicialEsquerdo"></param> /// <param name="pixelInicialInicio"></param> /// <param name="larguraPixel"></param> /// <param name="alturaPixel"></param> /// <param name="percentualBrilho"></param> /// <param name="percentualContraste"></param> /// <param name="modoCor"></param> private static void AjustaPropriedadesDispositivo(IItem item, int pixelInicialEsquerdo, int pixelInicialInicio, int percentualBrilho, int percentualContraste, int modoCor, WIAScanQuality qualidade, WIAPageSize tamanho) { const string WIA_SCAN_COLOR_MODE = "6146"; const string WIA_HORIZONTAL_SCAN_RESOLUTION_DPI = "6147"; const string WIA_VERTICAL_SCAN_RESOLUTION_DPI = "6148"; const string WIA_HORIZONTAL_SCAN_START_PIXEL = "6149"; const string WIA_VERTICAL_SCAN_START_PIXEL = "6150"; const string WIA_HORIZONTAL_SCAN_SIZE_PIXELS = "6151"; const string WIA_VERTICAL_SCAN_SIZE_PIXELS = "6152"; const string WIA_SCAN_BRIGHTNESS_PERCENTS = "6154"; const string WIA_SCAN_CONTRAST_PERCENTS = "6155"; // adjust the scan settings int resolucaoDPI; int larguraPixel; int alturaPixel; switch (qualidade) { case WIAScanQuality.Preview: resolucaoDPI = 100; break; case WIAScanQuality.Final: resolucaoDPI = 100; break; default: throw new Exception("Qualidade da imagem inválida: " + qualidade.ToString()); } switch (tamanho) { case WIAPageSize.A4: larguraPixel = (int)(8.3f * resolucaoDPI); alturaPixel = (int)(11f * resolucaoDPI); break; case WIAPageSize.Letter: larguraPixel = (int)(8.5f * resolucaoDPI); alturaPixel = (int)(11f * resolucaoDPI); break; case WIAPageSize.Legal: larguraPixel = (int)(8.5f * resolucaoDPI); alturaPixel = (int)(11f * resolucaoDPI); break; default: throw new Exception("Tamanho da página inválido: " + tamanho.ToString()); } GravaPropriedadeWIA(item.Properties, WIA_HORIZONTAL_SCAN_RESOLUTION_DPI, resolucaoDPI); GravaPropriedadeWIA(item.Properties, WIA_VERTICAL_SCAN_RESOLUTION_DPI, resolucaoDPI); GravaPropriedadeWIA(item.Properties, WIA_HORIZONTAL_SCAN_START_PIXEL, pixelInicialEsquerdo); GravaPropriedadeWIA(item.Properties, WIA_VERTICAL_SCAN_START_PIXEL, pixelInicialInicio); GravaPropriedadeWIA(item.Properties, WIA_HORIZONTAL_SCAN_SIZE_PIXELS, larguraPixel); GravaPropriedadeWIA(item.Properties, WIA_VERTICAL_SCAN_SIZE_PIXELS, alturaPixel); GravaPropriedadeWIA(item.Properties, WIA_SCAN_BRIGHTNESS_PERCENTS, percentualBrilho); GravaPropriedadeWIA(item.Properties, WIA_SCAN_CONTRAST_PERCENTS, percentualContraste); GravaPropriedadeWIA(item.Properties, WIA_SCAN_COLOR_MODE, modoCor); }
/// <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); }