public static List<System.Drawing.Image> preScan() { WIA.ICommonDialog dialog = new WIA.CommonDialog(); WIA.Device device = dialog.ShowSelectDevice(WIA.WiaDeviceType.UnspecifiedDeviceType, true, false); if (device != null) { return preScan(device.DeviceID); } else { throw new Exception("You must select a device for scanning."); } }
private void button1_Click(object sender, EventArgs e) { const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"; String Archivo = "D:\\EJEMPLO_ESCANEO_012"; //CommonDialogClass wiaDiag = new CommonDialogClass(); ICommonDialog wiaDiag = new WIA.CommonDialog(); WIA.ImageFile wiaImage = null; wiaImage = wiaDiag.ShowAcquireImage(WiaDeviceType.UnspecifiedDeviceType,WiaImageIntent.GrayscaleIntent,WiaImageBias.MaximizeQuality, wiaFormatJPEG , true, true, false ); WIA.Vector vector = wiaImage.FileData; pictureBox1.Image = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData())); Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData())); i.Save(Archivo + ".TIFF"); PdfSharp.Pdf.PdfDocument doc = new PdfSharp.Pdf.PdfDocument(); doc.Pages.Add(new PdfSharp.Pdf.PdfPage()); PdfSharp.Drawing.XGraphics xgr = PdfSharp.Drawing.XGraphics.FromPdfPage(doc.Pages[0]); PdfSharp.Drawing.XImage img = PdfSharp.Drawing.XImage.FromFile(Archivo + ".TIFF"); xgr.DrawImage(img, 0, 0); doc.Save(Archivo + ".PDF"); doc.Close(); }
/// <summary> /// Use scanner to scan an image (scanner is selected by its unique id). /// </summary> /// <param name="scannerName"></param> /// <returns>Scanned images.</returns> public override List<Image> Scan() { Console.WriteLine("Scan WIA"); 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 == 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 { foreach (Property prop in item.Properties) { switch (prop.PropertyID) { case 6146: //1 : couleur, 2 : gris, 4 : binaire SetProperty(prop, 2); break; case 6147: //ppp horizontal SetProperty(prop, MainWindow.numerisationDPI); break; case 6148: //ppp vertical SetProperty(prop, MainWindow.numerisationDPI); break; case 6149: //x point where to start scan SetProperty(prop, 0); break; case 6150: //y-point where to start scan SetProperty(prop, 0); break; } } // scan image WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog(); WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, EnvFormatID.wiaFormatTIFF, false); if(image == null) { Console.WriteLine("Numérisation annulé"); return null; } // 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 (System.ArgumentException e) { Console.WriteLine("Le PPP spécifié n'est pas supporté par le scanner"); throw e; } 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) { const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"; String Archivo = "D:\\EJEMPLO_ESCANEO_012"; //CommonDialogClass wiaDiag = new CommonDialogClass(); ICommonDialog wiaDiag = new WIA.CommonDialog(); WIA.ImageFile wiaImage = null; wiaImage = wiaDiag.ShowAcquireImage(WiaDeviceType.UnspecifiedDeviceType, WiaImageIntent.GrayscaleIntent, WiaImageBias.MaximizeQuality, wiaFormatJPEG, true, true, false); WIA.Vector vector = wiaImage.FileData; pictureBox1.Image = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData())); Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData())); i.Save(Archivo + ".TIFF"); PdfSharp.Pdf.PdfDocument doc = new PdfSharp.Pdf.PdfDocument(); doc.Pages.Add(new PdfSharp.Pdf.PdfPage()); PdfSharp.Drawing.XGraphics xgr = PdfSharp.Drawing.XGraphics.FromPdfPage(doc.Pages[0]); PdfSharp.Drawing.XImage img = PdfSharp.Drawing.XImage.FromFile(Archivo + ".TIFF"); xgr.DrawImage(img, 0, 0); doc.Save(Archivo + ".PDF"); doc.Close(); }
private void digitalizarToolStripButton_Click(object sender, EventArgs e) { const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"; var wiaDiag = new WIA.CommonDialog(); // instanciando a WiaImagem WIA.ImageFile wiaImage = null; //objeto criado para fins de fazer scanear varios documentos de uma vez int i = 1; //objeto criado para fins de fazer scanear varios documentos de uma vez object index = 1; // capturando a imgaem scaneada e abrindo o pop-up do scanner wiaImage = wiaDiag.ShowAcquireImage( WiaDeviceType.UnspecifiedDeviceType, WiaImageIntent.GrayscaleIntent, WiaImageBias.MaximizeQuality, wiaFormatJPEG, true, true, false); //pegando o WiaImage e vetorizando WIA.Vector vector = wiaImage.FileData; // carregando a imagem em memoria Image img = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData())); img.Save("C:/imagem" + i + ".jpg"); }
private void loadScanner() { wia_dialog = new WIA.CommonDialog(); scanner = wia_dialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false); if (scanner == null) { MessageBox.Show("Nie wykryto skanera"); } }
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 = }
private void button2_Click(object sender, EventArgs e) { try { commonDialog = new CommonDialog(); countScannings++; chooseScanner(); Device connectedDevice = scanner.Connect(); Item scannerItem = connectedDevice.Items[1]; AdjustScannerSettings(scannerItem, resolution, 0, 0, scanWidth, scanHeight, scanBrightness, scanContrast, scanColorMode); SetDeviceIntProperty(ref connectedDevice, 3088, 1); SetDeviceIntProperty(ref connectedDevice, 3096, 1); ImageFile image = commonDialog.ShowTransfer(scannerItem, formatID, true); filePath += @"\"; filePath += countScannings.ToString(); filePath += "scan"; if (radioButtonBMP.Checked) { filePath += ".bmp"; } if (radioButtonPNG.Checked) { filePath += ".png"; } if (radioButtonJPEG.Checked) { filePath += ".jpeg"; } if (radioButtonTIFF.Checked) { filePath += ".tiff"; } if (File.Exists(filePath)) { File.Delete(filePath); } image.SaveFile(filePath); MessageBox.Show(success); Image image2 = Image.FromFile(filePath); pictureBox1.Image = ResizeImage(image2, pictureBox1.Width, pictureBox1.Height); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void deviceInfoToolStripMenuItem_Click(object sender, EventArgs e) { WIA.ICommonDialog commonDialogClass = new WIA.CommonDialog(); Device scannerDevice = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false); Item scannnerItem = scannerDevice.Items[1]; String str = ""; foreach (Property prop in scannnerItem.Properties) { str += "\n" + prop.Name + " " + prop.PropertyID + " " + prop.get_Value(); } MessageBox.Show(str, "Device Information", MessageBoxButtons.OK, MessageBoxIcon.Information); }
/// <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."); } }
private void button1_Click(object sender, EventArgs e) { const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"; WIA.CommonDialog wiaDiag = new WIA.CommonDialog(); WIA.ImageFile wiaImage = null; wiaImage = wiaDiag.ShowAcquireImage(WiaDeviceType.UnspecifiedDeviceType, WiaImageIntent.GrayscaleIntent, WiaImageBias.MaximizeQuality, wiaFormatJPEG, true, true, false); WIA.Vector vector = wiaImage.FileData; Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData())); pictureBox.Image = i; }
public void GetDefaultDeviceID() { // Select a scanner WIA.CommonDialog wiaDiag = new WIA.CommonDialog(); Device d = wiaDiag.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false); if (d != null) { this.DeviceId = d.DeviceID; FindDevice(); this._device = this.deviceInfo.Connect(); } }
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> /// Scan a image with JPEG Format /// </summary> /// <returns></returns> public ImageFile ScanJPEG() { // Connect to the device and instruct it to scan // Connect to the device var device = this._deviceInfo.Connect(); // Select the scanner WIA.CommonDialog dlg = new WIA.CommonDialog(); var item = device.Items[1]; try { AdjustScannerSettings(item, resolution, 0, 0, width_pixel, height_pixel, 0, 0, color_mode); object scanResult = dlg.ShowTransfer(item, EnvFormatID.wiaFormatJPEG, true); if (scanResult != null) { var imageFile = (ImageFile)scanResult; // Return the imageFile return(imageFile); } } catch (COMException e) { // Display the exception in the console. Console.WriteLine(e.ToString()); uint errorCode = (uint)e.ErrorCode; // Catch 2 of the most common exceptions 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 { MessageBox.Show("A non catched error occurred, check the console. Error code: " + errorCode, "Error", MessageBoxButtons.OK); } } return(new ImageFile()); }
/// <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."); } }
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); } }
private string FindDefaultDeviceId() { if (String.IsNullOrEmpty(deviceId)) { // Select a scanner WIA.CommonDialog wiaDiag = new WIA.CommonDialog(); Device d = wiaDiag.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false); if (d != null) { deviceId = d.DeviceID; } } return deviceId; }
/// <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); }
private void btnScan_Click(object sender, EventArgs e) { try { WIA.CommonDialog dialog = new WIA.CommonDialog(); ImageFile scannedImage = null; scannedImage = dialog.ShowAcquireImage( WiaDeviceType.ScannerDeviceType, WiaImageIntent.UnspecifiedIntent, WiaImageBias.MaximizeQuality, FormatID.wiaFormatPNG, true, true, false); if (scannedImage != null) { WIA.Vector vector = scannedImage.FileData; byte[] b = (byte[])vector.get_BinaryData(); System.Drawing.Image img = System.Drawing.Image.FromStream(new System.IO.MemoryStream(b)); pictureBox1.Image = img; pictureBox1.Height = img.Height; pictureBox1.Width = img.Width; pictureBox1.Image = img; } }catch (Exception ex) { Scanner scanner = new Scanner(); ArrayList list = scanner.ADFScan(); if (list.Count <= 0) { MessageBox.Show("خطا در دستیابی به اسکنر ، لطفا از وصل بودن کابلهای اسکنر اطمینان حاصل کنید" + "\n" + ex.Message); } else { WIA.Vector vector = ((ImageFile)list[0]).FileData; byte[] b = (byte[])vector.get_BinaryData(); System.Drawing.Image img = System.Drawing.Image.FromStream(new System.IO.MemoryStream(b)); pictureBox1.Image = img; pictureBox1.Height = img.Height; pictureBox1.Width = img.Width; pictureBox1.Image = img; } } }
private bool SelectDevice() { try { // ISSUE: variable of a compiler-generated type WIA.CommonDialog commonDialog = (WIA.CommonDialog)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("850D1D11-70F3-4BE5-9A11-77AA6B2BB201"))); // ISSUE: reference to a compiler-generated method // ISSUE: variable of a compiler-generated type Device device = commonDialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, true); this._deviceId = device.DeviceID; } catch (Exception ex) { Console.Error.WriteLine("Failed to select scanner"); Console.Error.WriteLine(ex.ToString()); } return(!string.IsNullOrEmpty(this._deviceId)); }
public bool Scan(ref ImageFile image) { bool success = false; try { WIA.CommonDialog dialog = new WIA.CommonDialog(); image = dialog.ShowAcquireImage( WiaDeviceType.ScannerDeviceType, WiaImageIntent.ColorIntent, WiaImageBias.MaximizeQuality, WIA.FormatID.wiaFormatJPEG, false, false, false); success = true; } catch {} return(success); }
public ImageFile Scan() { try { WIA.CommonDialog dialog = new WIA.CommonDialog(); ImageFile image = dialog.ShowAcquireImage( WiaDeviceType.ScannerDeviceType, WiaImageIntent.ColorIntent, WiaImageBias.MaximizeQuality, WIA.FormatID.wiaFormatJPEG, false, false, false); return(image); } catch { MessageBox.Show("Таны Scanner бэлэн биш байна ."); return(null); } }
private void PerformDialogAtion(Action <Device, CommonDialog> action, bool allowNullDevice = false) { Device device; device = this.GetSelectedDevice(); if (device != null || allowNullDevice) { CommonDialog dialog; dialog = new CommonDialog(); action(device, dialog); } else { MessageBox.Show("No device selected.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
ImageFile Scan(String str) { LogContent("process", "Scanning"); CommonDialog dialog = new WIA.CommonDialog(); ImageFile scannedImage = null; if (Set.default_device == null) { WiaDev = dialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false); MessageBoxResult result = MessageBox.Show("Ustawić urządzenie jako domyślne?", "Potwierdzenie", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { Set.default_device = WiaDev; } } else { WiaDev = Set.default_device; } //Start Scan WIA.Item Item = WiaDev.Items[1] as WIA.Item; try { scannedImage = (ImageFile)dialog.ShowTransfer(Item, EnvFormatID.wiaFormatPNG, false); String path = Set.path; destination = path + str + "_" + Note.Text + ".png"; LogContent("destination", destination); scannedImage.SaveFile(destination); return(scannedImage); } catch (Exception e) { MessageBox.Show("Error " + e.Message); } finally { } return(null); }
/// <summary> /// Select Scanner. /// If you need to save the Scanner, Save WiaWrapper.DeviceID /// </summary> public void SelectScanner() { WIA.CommonDialog wiaDiag = new WIA.CommonDialog(); try { Device d = wiaDiag.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false); if (d != null) { DeviceID = d.DeviceID; return; } } catch (Exception ex) { throw new Exception("Error, Is a scanner chosen?"); } throw new Exception("No Device Selected"); }
private void Scan_Click(object sender, RoutedEventArgs e) { ICommonDialog dialog = new WIA.CommonDialog(); DeviceInfo device = null; for (int i = 1; i <= manager.DeviceInfos.Count; i++) { if (manager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) { continue; } device = manager.DeviceInfos[i]; break; } if (device == null) { MessageBox.Show("Scanner doesn't attached", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); return; } var d = device.Connect(); Item item = d.Items[1]; SetWIAProperty(item.Properties, WIA_HORIZONTAL_SCAN_RESOLUTION_DPI, 300); SetWIAProperty(item.Properties, WIA_VERTICAL_SCAN_RESOLUTION_DPI, 300); ImageFile image = (ImageFile)dialog.ShowTransfer(item, FormatID.wiaFormatJPEG, true); if (image == null) { return; } imageBytes = (byte[])image.FileData.get_BinaryData(); OriginalImage = (Bitmap)Image.FromStream(new MemoryStream(imageBytes)); OriginalImage.RotateFlip(RotateFlipType.Rotate90FlipNone); CroppedImage = OriginalImage.Clone() as Bitmap; ImageScale = (float)Width / OriginalImage.Width; MakeScaledImage(); }
public List <Image> Scan() { const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"; //CommonDialogClass wiaDiag = new CommonDialogClass(); ICommonDialog wiaDiag = new WIA.CommonDialog(); WIA.ImageFile wiaImage = null; wiaImage = wiaDiag.ShowAcquireImage(WiaDeviceType.ScannerDeviceType, WiaImageIntent.UnspecifiedIntent, WiaImageBias.MaximizeQuality, WIA_FORMAT_JPEG, false, true, false); List <Image> images = new List <Image>(); if (wiaImage != null) { System.Diagnostics.Trace.WriteLine(String.Format("Image is {0} x {1} pixels", (float)wiaImage.Width / 150, (float)wiaImage.Height / 150)); Image image = ConvertToImage(wiaImage); images.Add(image); } 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, 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); }
public string GetTestInfo() { try { StringBuilder sb = new StringBuilder(); // create a new WIA common dialog box for the user to select a device from CommonDialog dlg = new CommonDialog(); // show user the WIA device dialog Device d = dlg.ShowSelectDevice(WiaDeviceType.CameraDeviceType, true, false); // check if a device was selected if (d != null) { // Print camera properties sb.Append("\n\n Print properties:\n"); foreach (Property p in d.Properties) { sb.Append(p.Name + ": " + p.get_Value() + " (" + p.PropertyID + ":" + p.IsReadOnly + ") \n"); // Update UI if (p.PropertyID == 3) sb.Append("prop 3 - " + (String)p.get_Value()); if (p.PropertyID == 4) sb.Append("prop 4 - " + (String)p.get_Value()); } // Print commands sb.Append("\n\n Print commands:\n"); foreach (DeviceCommand dvc in d.Commands) { sb.Append(dvc.Name + ": " + dvc.Description + " (" + dvc.CommandID + ") \n"); } // Print events sb.Append("\n\n Print events:\n"); foreach (DeviceEvent dve in d.Events) { sb.Append(dve.Name + ": " + dve.Description + " (" + dve.Type + ") \n"); } // Print item properties sb.Append("\n\n Print item properties:\n"); foreach (Property item in d.Items[1].Properties) { sb.Append(item.IsReadOnly + ": " + item.Name + " (" + item.PropertyID + ") \n"); } foreach (Property p in d.Properties) { Object tempNewProperty; // change Exposure Compensation: value 0 to 2 (ID 2053, isReadonly False) if (p.PropertyID == 2053) { tempNewProperty = (int)-2000; // can not be set to minus values, why??? ((IProperty)p).set_Value(ref tempNewProperty); sb.Append(">>>>" + p.get_Value()); } } // Now let's take a picture ! d.ExecuteCommand(CommandID.wiaCommandTakePicture); sb.Append("."); } else { sb.Append("Result: no device selected or device could not be read. "); } return sb.ToString(); } catch (Exception ex) { return "Камера не подключена"; } }
/// <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); }
private string GetDefaultDeviceID() { string deviceId = Properties.Settings.Default.ScannerDeviceID; if (String.IsNullOrEmpty(deviceId)) { // Select a scanner WIA.CommonDialog wiaDiag = new WIA.CommonDialog(); Device d = wiaDiag.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false); if (d != null) { deviceId = d.DeviceID; Properties.Settings.Default.ScannerDeviceID = deviceId; Properties.Settings.Default.Save(); } // Register for the scanner button event //string eventId = ""; //DeviceManager manager = new DeviceManager(); //string command = String.Format("{0} {1}", Application.ExecutablePath, "/StiDevice:%1"); //string description = "Converts scanned documents to PDF and uploads to Evernote"; //string icon = String.Format("{0},0", Application.ExecutablePath); //// Affects registry keys //// HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\StillImage\Events\EVENT_ID //// HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Control\StillImage\Events\EVENT_ID //// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StillImage\Events\EVENT_ID //manager.RegisterPersistentEvent(command, "ScanToEvernote", description, icon, eventId, deviceId); } return deviceId; }
/// <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 scanButton_Click(object sender, RoutedEventArgs e) { //filePath = namefile(); filePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(),"RESUME_SCANNER_image.tif"); System.IO.File.Delete(filePath); dialog = new WIA.CommonDialog(); try { scanner = dialog.ShowSelectDevice( WiaDeviceType.ScannerDeviceType, false, false); } catch (Exception msg) { //Uri uri = new Uri("Images/scanned.tif", UriKind.Relative); Uri uri = new Uri("Images/nnenna_u_resume.tif", UriKind.Relative); var stream = Application.GetResourceStream(uri).Stream; using (FileStream fileStream = System.IO.File.Create(filePath, (int)stream.Length)) { // Fill the bytes[] array with the stream data byte[] bytesInStream = new byte[stream.Length]; stream.Read(bytesInStream, 0, (int)bytesInStream.Length); // Use FileStream object to write to the specified file fileStream.Write(bytesInStream, 0, bytesInStream.Length); } } if (scanner!=null) { foreach (Property item in scanner.Items[1].Properties) { switch (item.PropertyID) { case 6146: //4 is Black-white,gray is 2, color 1 SetProperty(item, 4); break; case 6147: //dots per inch/horizontal SetProperty(item, 300); break; case 6148: //dots per inch/vertical SetProperty(item, 300); break; case 6149: //x point where to start scan SetProperty(item, 0); break; case 6150: //y-point where to start scan SetProperty(item, 0); break; case 3096: //Pages SetProperty(item, 1); break; case 3097: //PageSize SetProperty(item, 1); break; case 6151: //horizontal exent SetProperty(item, (int)(8.5 * 300)); break; case 6152: //vertical extent SetProperty(item, (int)(11 * 300)); break; case 4103: //DataType SetProperty(item, 0); break; case 4104: //BitsPerPixel SetProperty(item, 1); break; case 4110: //BitsPerChannel SetProperty(item, 1); break; case 4114: //NumberOfLines SetProperty(item, 3300); break; case 4116: //ItemSize SetProperty(item, 1056062); break; case 4113: //Bytes Per Line SetProperty(item, 320); break; } } dialog.ShowSelectItems(scanner); ImageFile image = null; try { image = dialog.ShowTransfer(scanner.Items[1], FormatID.wiaFormatTIFF, false) as ImageFile; } catch (Exception msg) { if (msg.Message.Contains("HRESULT")) MessageBox.Show("Please insert paper into scanner and try again."); return; } //System.IO.File.Delete(filePath); image.SaveFile(filePath); } BitmapImage _image = new BitmapImage(); _image.BeginInit(); _image.CacheOption = BitmapCacheOption.None; _image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache); _image.CacheOption = BitmapCacheOption.OnLoad; _image.CreateOptions = BitmapCreateOptions.IgnoreImageCache; _image.UriSource = new Uri(filePath, UriKind.RelativeOrAbsolute); _image.EndInit(); scannedImageHolder.Source = _image; }
public static List<System.Drawing.Image> preScan(string scannerId) { List<System.Drawing.Image> images = new List<System.Drawing.Image>(); bool hasMorePages = true; while (hasMorePages) { WIA.DeviceManager manager = new WIA.DeviceManager(); WIA.Device device = null; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == scannerId) { device = info.Connect(); break; } } if (device == null) { 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 { 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(System.Drawing.Image.FromFile(fileName)); } catch (Exception exc) { throw exc; } finally { item = null; } 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; }
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); }
/// <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 (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> /// Use scanner to scan an image (with user selecting the scanner from a dialog). /// </summary> /// <returns>Scanned images.</returns> public NumerisationWIA() { WIA.ICommonDialog dialog = new WIA.CommonDialog(); WIA.Device device = null; try { device = dialog.ShowSelectDevice (WIA.WiaDeviceType.UnspecifiedDeviceType, true, false); }catch(Exception e) { Console.WriteLine(e); Console.WriteLine("Problème lors de la communication avec le scanner : vérifiez les branchements, que le scanner est allumé et réessayez"); throw new Exception(); } if (device != null) { this.deviceID = device.DeviceID; this.ready = true; } }