private static WIA.Device LocalizaDispositio(string scannerId) { 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); } return(device); }
/// <summary> /// Realiza conexão com o dispositivo de câmera. /// </summary> /// <param name="cameraInfo">Dispositivo de câmera a ser conectado.</param> /// <returns>True, se a conexão foi estabelecida e false, caso contrário.</returns> public bool ConnectToDevice(WIACameraInfo cameraInfo) { // cria um novo gerenciador de dispositivos WIA.DeviceManagerClass deviceMgr = new WIA.DeviceManagerClass(); try { // flag para indicar se encontrou ou não o dispositivo bool foundDevice = false; // procura pelo dispositivo foreach (WIA.DeviceInfo deviceInfo in deviceMgr.DeviceInfos) { if (deviceInfo.DeviceID == cameraInfo.DeviceID) { // tenta conexão com o dispositivo this.connectedDevice = deviceInfo.Connect(); foundDevice = true; break; } } // verifica se encontrou dispositivo return(foundDevice); } catch { return(false); } }
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 = }
/// <summary> /// Seleciona a impressora a ser utilziada para digitalizar um documento /// O usuário deve escolher onde salvar a imagem /// </summary> /// <param name="dialog"></param> public static void ScanningToDisk() { ////http://www.andrealveslima.com.br/blog/index.php/2015/12/16/como-escanear-documentos-com-o-c-digitalizacao-de-documentos/ CommonDialogClass dialog = new WIA.CommonDialogClass(); WIA.Device scanner = dialog.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, true, false); if (scanner != null) { dialog.ShowAcquisitionWizard(scanner); } }
private void SetDeviceIntProperty(ref WIA.Device device, int propertyID, int propertyValue) { foreach (WIA.Property p in device.Properties) { if (p.PropertyID == propertyID) { object value = propertyValue; p.set_Value(ref value); break; } } }
/// <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> /// Libera recursos de memória. /// </summary> /// <param name="disposing">Se true, o método foi chamado diretamente ou /// indiretamente pelo código do usuário, se false, foi chamado pela CLR.</param> private void Dispose(bool disposing) { // verifica se Dispose já foi chamada if (!this.disposed) { if (disposing) { this.connectedDevice = null; } this.disposed = true; } }
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."); } }
public WIA.Device GetFirstWiaDevice() { WIA.DeviceManager mgr = new WIA.DeviceManager(); WIA.Device retVal = null; foreach (WIA.DeviceInfo info in mgr.DeviceInfos) { if (info.Type == WIA.WiaDeviceType.ScannerDeviceType) { return(mgr.DeviceInfos.OfType <DeviceInfo>().FirstOrDefault(o => o.DeviceID == info.DeviceID).Connect()); } } return(retVal); }
private void button1_Click(object sender, EventArgs e) { withFeeder = false; WIA.ImageFile Img = null; Scanner = null; try { if (Scanner == null) { if (chooseDevice()) { InitializeITEM(); //inicjuje ustawienia skanera Img = (ImageFile)Dialog1.ShowTransfer(Scanner.Items[1], wiaFormatBMP, true); imageBytes = (byte[])Img.FileData.get_BinaryData(); // <– Converts the ImageFile to a byte array MemoryStream ms = new MemoryStream(imageBytes); Image image = Image.FromStream(ms); pictureBox1.Image = image; } else { InitializeITEM(); //inicjuje ustawienia skanera Img = (ImageFile)Dialog1.ShowTransfer(Scanner.Items[1], wiaFormatBMP, true); imageBytes = (byte[])Img.FileData.get_BinaryData(); // <– Converts the ImageFile to a byte array MemoryStream ms = new MemoryStream(imageBytes); Image image = Image.FromStream(ms); pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage; pictureBox1.Image = image; return; } } else { InitializeITEM();//inicjuje ustawienia skanera Img = (ImageFile)Dialog1.ShowTransfer(Scanner.Items[1], wiaFormatBMP, true); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Skanuj...", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (Img != null) { Marshal.ReleaseComObject(Img); } } }
/// <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."); } }
/// <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)); } }
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); } }
public static WIA.Device ConnectToScanner(string scannerDeviceID) { WIA.DeviceManager manager = new WIA.DeviceManager(); WIA.Device device = null; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == scannerDeviceID) { device = info.Connect(); break; } } return(device); }
/// <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."); } }
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); }
public WIA.ImageFile ScanAndSaveOnePage() { WIA.CommonDialog Dialog1 = new WIA.CommonDialogClass(); WIA.DeviceManager DeviceManager1 = new WIA.DeviceManagerClass(); System.Object Object1 = null; System.Object Object2 = null; WIA.Device Scanner = null; try { Scanner = Dialog1.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, false, false); } catch { MessageBox.Show("请确认是否联系设备"); return(null); throw; } WIA.Item Item1 = Scanner.Items[1]; setItem(Item1, "4104", 24); setItem(Item1, "6146", 2); setItem(Item1, "6147", 150); setItem(Item1, "6148", 150); setItem(Item1, "6151", 150 * 8.5); setItem(Item1, "6152", 150 * 11); WIA.ImageFile Image1 = new WIA.ImageFile(); WIA.ImageProcess ImageProcess1 = new WIA.ImageProcess(); Object1 = (Object)"Convert"; ImageProcess1.Filters.Add(ImageProcess1.FilterInfos.get_Item(ref Object1).FilterID, 0); Object1 = (Object)"FormatID"; Object2 = (Object)WIA.FormatID.wiaFormatBMP; ImageProcess1.Filters[1].Properties.get_Item(ref Object1).set_Value(ref Object2); Object1 = null; Object2 = null; Image1 = (WIA.ImageFile)Item1.Transfer(WIA.FormatID.wiaFormatBMP); return(Image1); //string DestImagePath = @"C:\test.bmp"; //File.Delete(DestImagePath); //Image1.SaveFile(DestImagePath); }
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); }
/// <summary> /// /// </summary> /// <param name="device"></param> /// <returns></returns> private static void CarregaPropriedades(WIA.Device device, Dictionary <string, string> mList) { try { // check if a device was selected if (device != null) { // Print camera properties foreach (Property prop in device.Properties) { mList.Add(prop.Name + "(dispositivo)", "(Valor) = " + prop.get_Value().ToString() + " (PropertyId = " + prop.PropertyID + ": IsReadOnly = " + prop.IsReadOnly + ")"); // Update UI } // Print item properties foreach (Property prop in device.Items[1].Properties) { mList.Add(prop.Name + "(item 1- dispositivo)", "(PropertyID) = " + prop.PropertyID.ToString() + " (IsReadOnly = " + prop.IsReadOnly.ToString() + ") \n"); } // Print commands foreach (DeviceCommand com in device.Commands) { mList.Add(com.Name + "(commandos)", "(Descrição) = " + com.Description + " (CommandId = " + com.CommandID + ")"); } // Print events foreach (DeviceEvent evt in device.Events) { mList.Add(evt.Name + "(events)", "(Descrição) = " + evt.Description + " (Type = " + evt.Type + ") \n"); } } } catch (Exception ex) { Mensagens.Add(ex.Message + "WIA Error!"); } }
/// <summary> /// Scan a single image /// </summary> public byte[] ScanSingle(ScannerInfo source) { WIA.Device wiaDevice = source.GetDevice(); // Manager WIA.DeviceManager wiaManager = new WIA.DeviceManager(); try { // Get items WIA.Item wiaItem = wiaDevice.Items[1]; int inColor = 2, dpi = 300; wiaItem.Properties["6146"].set_Value((int)inColor);//Item MUST be stored in a variable THEN the properties must be set. wiaItem.Properties["6147"].set_Value(dpi); wiaItem.Properties["6148"].set_Value(dpi); var imageFile = (ImageFile)(new CommonDialog()).ShowTransfer(wiaItem, "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}", false); //wiaItem.Transfer("{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}") as WIA.ImageFile; return(imageFile.FileData.get_BinaryData()); } catch (Exception e) { throw; } }
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 = ""; } }
/// <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 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; }
/// <summary> /// Use scanner to scan an image (scanner is selected by its unique id). /// </summary> /// <param name="scannerName"></param> /// <returns>Scanned images.</returns> public List <Image> Scan(string scannerId, int pages) { //List<Image> images = new List<Image>(); bool hasMorePages = true; int numbrPages = pages; // select the correct scanner using the provided scannerId parameter WIA.DeviceManager manager = new WIA.DeviceManager(); WIA.Device device = null; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == scannerId) { // connect to scanner device = info.Connect(); break; } } // device was not found if (device == null) { // enumerate available devices string availableDevices = ""; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { availableDevices += info.DeviceID + "\n"; } // show error with available devices throw new Exception("The device with provided ID could not be found. Available Devices:\n" + availableDevices); } SetWIAProperty(device.Properties, WIA_DEVICE_PROPERTY_PAGES_ID, 1); item = device.Items[1] as WIA.Item; int dpi = 300; int inch = 254; double dpiMM = dpi / inch; double widthFormat = 210; double heightFormat = 297; int widthPixel = (int)(widthFormat * dpiMM); int heightPixel = (int)(heightFormat * dpiMM); AdjustScannerSettings(item, dpi, 0, 0, widthPixel, heightPixel, 0, 0, 2); while (hasMorePages) { Thread thread = new Thread(goScan); thread.Start(); thread.Join(); /* * finally * { * //item = null; * //determine if there are any more pages waiting * WIA.Property documentHandlingSelect = null; * WIA.Property documentHandlingStatus = null; * foreach (WIA.Property prop in device.Properties) * { * if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT) * documentHandlingSelect = prop; * if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS) * documentHandlingStatus = prop; * } * // assume there are no more pages * hasMorePages = false; * // may not exist on flatbed scanner but required for feeder * if (documentHandlingSelect != null) * { * // check for document feeder * if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0) * { * hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0); * } * } * } */ numbrPages -= 1; if (numbrPages > 0) { hasMorePages = true; } else { hasMorePages = false; } } return(images); }
/// <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> /// 扫描仪器 /// </summary> private void GetDevice() { // This will show the select device dialog to choose which device to use try { CommonDialogClass MyDialog = new CommonDialogClass(); //Device MyDevice = MyDialog.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, false, true); Device MyDevice = null; if (rdothers.Checked == true) { MyDevice = MyDialog.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, false, true); } //else if (MyDevice.Type == WIA.WiaDeviceType.CameraDeviceType) else if (rdothers.Checked == true) { MyDevice = MyDialog.ShowSelectDevice(WIA.WiaDeviceType.CameraDeviceType, false, true); // rdCamera.Checked = true; } if ((MyDevice != null)) { //loops through device properties, only gets the ones we want to display foreach (WIA.Property prop in MyDevice.Properties) { switch (prop.Name) { case "Manufacturer": lblMfg.Text = Convert.ToString(prop.get_Value()); break; case "Description": lblDesc.Text = Convert.ToString(prop.get_Value()); break; case "Name": lblName.Text = Convert.ToString(prop.get_Value()); break; case "WIA Version": lblWIA.Text = Convert.ToString(prop.get_Value()); break; case "Driver Version": lblDriver.Text = Convert.ToString(prop.get_Value()); break; } } //sets MyDevice form level selected device SelectedDevice = MyDevice; btncapture.Enabled = true; } else { lblName.Text = "No WIA Devices Found!"; MessageBox.Show("No WIA Devices Found!"); } } catch (System.Exception ex) { MessageBox.Show("Problem! " + ex.Message, "Problem Loading Device", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); } }
/// <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); }
private void button1_Click(object sender, EventArgs e) { withFeeder = false; WIA.ImageFile Img = null; Scanner = null; try { if (Scanner == null) if (chooseDevice()) { InitializeITEM();//inicjuje ustawienia skanera Img = (ImageFile)Dialog1.ShowTransfer(Scanner.Items[1], wiaFormatBMP, true); imageBytes = (byte[])Img.FileData.get_BinaryData(); // <– Converts the ImageFile to a byte array MemoryStream ms = new MemoryStream(imageBytes); Image image = Image.FromStream(ms); pictureBox1.Image = image; } else { InitializeITEM();//inicjuje ustawienia skanera Img = (ImageFile)Dialog1.ShowTransfer(Scanner.Items[1], wiaFormatBMP, true); imageBytes = (byte[])Img.FileData.get_BinaryData(); // <– Converts the ImageFile to a byte array MemoryStream ms = new MemoryStream(imageBytes); Image image = Image.FromStream(ms); pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage; pictureBox1.Image = image; return; } else { InitializeITEM();//inicjuje ustawienia skanera Img = (ImageFile)Dialog1.ShowTransfer(Scanner.Items[1], wiaFormatBMP, true); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Skanuj...", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (Img != null) Marshal.ReleaseComObject(Img); } }
/// <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 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 }