public Image Scan(DeviceInfo device) { if (device == null) throw new ArgumentException("Device must be specified"); var scanner = device.Connect(); var wiaCommonDialog = new WPFCommonDialog(); var item = scanner.Items[1]; var image = (ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false); string fileName = Path.GetTempFileName(); File.Delete(fileName); image.SaveFile(fileName); image = null; // add file to output list return Image.FromFile(fileName); }
public Image Scan(DeviceInfo device, PageSize pageSize, ColorDepth colorDepth, Resolution resolution, Orientation orientation, bool setSize = true) { if (device == null) { throw new ArgumentException("Device must be specified"); } var scanner = device.Connect(); var wiaCommonDialog = new WPFCommonDialog(); var item = scanner.Items[1]; SetupPageSize(item, pageSize, colorDepth, resolution, orientation, setSize); var image = (ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false); string fileName = Path.GetTempFileName(); File.Delete(fileName); image.SaveFile(fileName); image = null; // add file to output list return(Image.FromFile(fileName)); }
private void BTNScan_Click(object sender, EventArgs e) { try { var devices = new DeviceManager(); DeviceInfo device = null; for (int i = 0; i < devices.DeviceInfos.Count; i++) { if (devices.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) { continue; } device = devices.DeviceInfos[i]; break; } if (device != null) { var deviceConnect = device.Connect(); var SelectScan = deviceConnect.Items[1]; var image = (ImageFile)SelectScan.Transfer(FormatID.wiaFormatJPEG); if (File.Exists("Scan.jpg")) { File.Delete("Scan.jpg"); } image.SaveFile("Scan.jpg"); picDoc.ImageLocation = "Scan.jpg"; } } catch (COMException) { } }
void DoWork() { var deviceManager = new DeviceManager(); DeviceInfo AvailableScanner = null; //for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++) // Loop Through the get List Of Devices. //{ // if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) // Skip device If it is not a scanner // { // continue; // } // AvailableScanner = deviceManager.DeviceInfos[i]; // break; //} var selectedDevice = lookUpEdit1.GetSelectedDataRow() as ScannerViewModels; AvailableScanner = deviceManager.DeviceInfos[selectedDevice.Id]; var device = AvailableScanner.Connect(); //Connect to the available scanner. var ScanerItem = device.Items[1]; // select the scanner. var imgFile = (ImageFile)ScanerItem.Transfer(); //Retrive an image in Jpg format and store it into a variable. this.scanImage = Image.FromStream(new MemoryStream((byte[])imgFile.FileData.get_BinaryData())); }
private ImageFile ScanOne() { ImageFile image = null; try { // find our device (scanner previously selected with commonDialog.ShowSelectDevice) DeviceManager manager = new DeviceManager(); DeviceInfo deviceInfo = null; foreach (DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == _deviceId) { deviceInfo = info; } } if (deviceInfo != null) { Device device = deviceInfo.Connect(); Item item = device.Items[1]; // configure item SetItemIntProperty(ref item, 6146, this.scanType); // 2 for greyscale, 4 for black & white, 1 for color if (this.scanType != 4) { SetItemIntProperty(ref item, 4104, 8); // bit depth } SetItemIntProperty(ref item, 6147, this.dpi); // 150 dpi SetItemIntProperty(ref item, 6148, this.dpi); // 150 dpi SetItemIntProperty(ref item, 6151, (int)(this.dpi * this.width)); // scan width SetItemIntProperty(ref item, 6152, (int)(this.dpi * this.height)); // scan height int deviceHandling = this.adf ? 1 : 2; // 1 for ADF, 2 for flatbed // configure device SetDeviceIntProperty(ref device, 3088, deviceHandling); int handlingStatus = GetDeviceIntProperty(ref device, 3087); if (handlingStatus == deviceHandling) { image = item.Transfer(JpegFormat); } } } catch (COMException ex) { image = null; // paper empty if ((uint)ex.ErrorCode != 0x80210003) { throw; } } return(image); }
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 btnScan_Click(object sender, EventArgs e) { try { var deviceManager = new DeviceManager(); DeviceInfo AvailableScanner = null; for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++) // Loop Through the get List Of Devices. { if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) // Skip device If it is not a scanner { continue; } AvailableScanner = deviceManager.DeviceInfos[i]; break; } var device = AvailableScanner.Connect(); //Connect to the available scanner. var ScannerItem = device.Items[1]; // select the scanner. var imgFile = (ImageFile)ScannerItem.Transfer(FormatID.wiaFormatJPEG); //Retrive an image in Jpg format and store it into a variable. //string Path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // string filePath = Path + @"\ImagesFolder-Scrapbooker"; //save the image in some path with filename. string Path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string fileName = DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".jpeg"; string filePath = Path + @"\ImagesFolder-Scrapbooker\" + fileName; if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } imgFile.SaveFile(filePath); pictureBox1.ImageLocation = filePath; //Call function to save the img to our database FileInfo fi = new FileInfo(filePath); string fileFormat = fi.Extension; long fileSize = fi.Length / 1000; addImageToFileTable(fileName, filePath, fileFormat, fileSize); } catch (COMException ex) { MessageBox.Show(ex.Message); } }
private void Escanear_Click(object sender, EventArgs e) { string Cedente = NombreCedente.Text; string CarpetaVersion = Application.StartupPath + @"\Biblioteca\" + NuevoId + @"\1\ "; try { var deviceManager = new DeviceManager(); DeviceInfo EscanerDisponible = null; for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++) //Lista de Dispositivos { if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) //Saltar si no es escaner { continue; } EscanerDisponible = deviceManager.DeviceInfos[i]; break; } Show(); var dispositivo = EscanerDisponible.Connect(); // Conectarse al escaner disponible var ItemEscaner = dispositivo.Items[1]; // Seleccionar el escaner var imgFile = (ImageFile)ItemEscaner.Transfer(FormatID.wiaFormatJPEG); // Conseguir imagen JPG y guardarla en variable String filename = Directory.GetFiles(CarpetaVersion, "*", SearchOption.TopDirectoryOnly).Length.ToString(); var Ubicacion = CarpetaVersion + filename + @".jpg"; // Guardar en la carpeta del nuevo cedente imgFile.SaveFile(Ubicacion); ImagenEscaneada.ImageLocation = Ubicacion; Hide(); ObtImagenes(); } catch (COMException ex) { MessageBox.Show(ex.Message); } }
private void button3_Click(object sender, EventArgs e) { try { var deviceManager = new DeviceManager(); DeviceInfo AvailableScanner = null; if (deviceManager.DeviceInfos.Count == 0) { MessageBox.Show("Δεν υπάρχουν διαθέσιμοι σαρωτές!"); } else { for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++) // Loop Through the get List Of Devices. { if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) // Skip device If it is not a scanner { continue; } AvailableScanner = deviceManager.DeviceInfos[i]; break; } var device = AvailableScanner.Connect(); //Connect to the available scanner. var ScanerItem = device.Items[1]; // select the scanner. var imgFile = (ImageFile)ScanerItem.Transfer(FormatID.wiaFormatJPEG); //Retrive an image in Jpg format and store it into a variable. var Path = @"Scan\ScanImg.jpg"; // save the image in some path with filename. if (File.Exists(Path)) { File.Delete(Path); } imgFile.SaveFile(Path); pictureBox1.ImageLocation = Path; } } catch (Exception exc) { MessageBox.Show(exc.Message); } }
public ActionResult Yazdir(dosyalar model) { var deviceManager = new DeviceManager(); DeviceInfo AvailableScanner = null; for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++) // tarayıcı listesi { if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) // tarayacı yoksa atla { continue; } AvailableScanner = deviceManager.DeviceInfos[i]; break; } var device = AvailableScanner.Connect(); //tarayıcıya bağlan var ScanerItem = device.Items[1]; var imgFile = (ImageFile)ScanerItem.Transfer(FormatID.wiaFormatJPEG); //var Path = @"C:\Users\HP\Desktop\ScannerTest\ScanImg.png"; Random rnd = new Random(); int sayi = rnd.Next(100, 999); string dosyaAdi = "TY" + DateTime.Now.ToString("yyyy-MM-dd-HH-'" + sayi + "'") + ".png"; string path = ControllerContext.HttpContext.Server.MapPath("~/Uploads/" + dosyaAdi); model.dosya_yolu = "/Uploads/" + dosyaAdi; model.dosya_tipi = "png"; model.dosya_adi = dosyaAdi; imgFile.SaveFile(path); if (_dosyaServis.DosyaKaydet(model) == true) { return(Json(true, JsonRequestBehavior.AllowGet)); } else { return(Json(false, JsonRequestBehavior.AllowGet)); } }
private void scan(object sender, EventArgs e) { device = firstDevice.Connect(); scannerItem = device.Items[1]; brightness = Int32.Parse(brightnessText.Text); contrast = Int32.Parse(contrastText.Text); AdjustScannerSettings(scannerItem, resolution, 0, 0, width_pixel, height_pixel, brightness, contrast, color_mode); var path = "temp" + index.ToString() + ".jpeg"; index++; imageFile = (ImageFile)scannerItem.Transfer(FormatID.wiaFormatJPEG); imageFile.SaveFile(path); this.bit.SizeMode = PictureBoxSizeMode.Zoom; bit.Image = new Bitmap(path); }
private void button1_Click(object sender, EventArgs e) { try { var deviceManager = new DeviceManager(); DeviceInfo AvaiableScanner = null; int resolutionValue = int.Parse(textBox1.Text); int brightValue = int.Parse(bright.Text); int contrastValue = int.Parse(textBox2.Text); for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++) { if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) { continue; } else { AvaiableScanner = deviceManager.DeviceInfos[i]; break; } } var device = AvaiableScanner.Connect(); var scannerItem = device.Items[1]; int scanWidth = (int)(resolutionValue * scaleWidth); //jak nie dziala zamienic na int int scanHeight = (int)(1.41 * scanWidth); AdjustScannerSettings(scannerItem, resolutionValue, scanHeight, scanWidth, brightValue, contrastValue); var imgfile = (ImageFile)scannerItem.Transfer(FormatID.wiaFormatJPEG); var path = "C:\\Users\\lab\\Links\\KowolikKrol\\vkplik.jpeg"; if (File.Exists(path)) { File.Delete(path); } imgfile.SaveFile(path); pictureBox1.ImageLocation = path; //do modyfikacji } catch (COMException ex) { MessageBox.Show(ex.Message); } }
private void connectButton_Click(object sender, EventArgs e) { deviceManager = new DeviceManager(); firstScannerAvailable = null; for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++) { if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) { continue; } firstScannerAvailable = deviceManager.DeviceInfos[i]; device = firstScannerAvailable.Connect(); connectedLabel.Text = "Connected to: " + firstScannerAvailable.Properties["Name"].get_Value(); scannerItem = device.Items[1]; break; } }
private void buttonStart_Click(object sender, EventArgs e) { var device = firstDevice.Connect(); var scannerItem = device.Items[1]; AdjustScannerSettings(scannerItem, resolution, 0, 0, width_pixel, height_pixel, jasnosc, kontrast, color_mode); imageFile = (ImageFile)scannerItem.Transfer(FormatID.wiaFormatJPEG); string path = @"C:\Users\Marcin\Desktop\Studia\Semestr 5\UP\Skaner\UPSkaner\scan.jpeg"; ///zmienic sciezke if (File.Exists(path)) { File.Delete(path); } imageFile.SaveFile(path); MessageBox.Show("Obraz został zapisany do pliku."); pictureBox1.ImageLocation = path; }
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 void scanImage() { if (scannerInfo != null) { var device = scannerInfo.Connect(); var scannerItem = device.Items[1]; var imageFile = (ImageFile)scannerItem.Transfer(FormatID.wiaFormatJPEG); var path = Directory.GetCurrentDirectory() + "\\ScannedImages\\scan.jpg"; if (File.Exists(path)) { File.Delete(path); } try { imageFile.SaveFile(path); }catch (Exception e) { System.Windows.MessageBox.Show(e.Message.ToString(), "Error"); } } }
private void btnScan_Click(object sender, EventArgs e) { // https://youtu.be/PwnCjZSnE_E // https://www.codesenior.com/sources/docs/tutorials/How-to-get-Images-From-Scanner-in-C-with-Windows-Image-AcqusitionWIA-Library-.pdf try { DeviceInfo availableScanner = GetScannerDeviceByName(ScannerName); if (availableScanner == null) { MessageBox.Show("Scanner does not exist"); return; } var device = availableScanner.Connect(); //device.Properties.get_Item("3088").set_Value(5); // Double scanning or dublex scanning //device.Properties.get_Item("3088").set_Value(1); // Single scanning or simplex scanning var scannerItem = device.Items[1]; scannerItem.Properties.get_Item("6147").set_Value(ScannerDpiHorizontal); // horizontal dpi scannerItem.Properties.get_Item("6148").set_Value(ScannerDpiVertical); // vertical dpi var imgFile = scannerItem.Transfer(FormatID.wiaFormatJPEG) as ImageFile; var path = OutputPath; if (File.Exists(path)) { File.Delete(path); } imgFile.SaveFile(path); pictureBox1.ImageLocation = path; } catch (COMException ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Rozpoczęcie skanowania /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonStartScanning_Click(object sender, EventArgs e) { try { // Połączenie z wybranym skanerem var connectedDevice = firstScannerAvailable.Connect(); // Wybranie obiektu skanowania var scannerItem = connectedDevice.Items[1]; // Ustawienie opcji skanera AdjustScannerSettings(scannerItem, resolution, 0, 0, documentWidth, documentHeight, brightness, contrast, colorMode); // Wykonanie skanowania scannedDocument = (ImageFile)scannerItem.Transfer("{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"); filePath += "\\scan.jpeg"; // Sprawdzenie czy ścieżka jest wolna if (File.Exists(filePath)) { File.Delete(filePath); } // Zapis do pliku scannedDocument.SaveFile(filePath); MessageBox.Show("Zeskanowany dokument został zapisany do pliku"); // Wyświetlenie zeskanowanego dokumentu w formie pictureBoxScannedDocument.ImageLocation = filePath; } catch (Exception) { MessageBox.Show("Wystąpił błąd podczas skanowania, upewnij się że odpowiedni skaner jest wybrany oraz podłączony"); } }
private void btnScan_Click(object sender, EventArgs e) { try { var deviceManager = new DeviceManager(); DeviceInfo availableScanner = null; for (var i = 1; i <= deviceManager.DeviceInfos.Count; i++) // Loop Through the get List Of Devices. { if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) // Skip device If it is not a scanner { continue; } availableScanner = deviceManager.DeviceInfos[i]; break; } if (availableScanner != null) { var device = availableScanner.Connect(); //Connect to the available scanner. var scanerItem = device.Items[1]; // select the scanner. var imgFile = (ImageFile)scanerItem.Transfer(FormatID .wiaFormatJPEG); //Retrieve an image in Jpg format and store it into a variable. var imageBytes = (byte[])imgFile.FileData.get_BinaryData(); var ms = new MemoryStream(imageBytes); var img = Image.FromStream(ms); pbContract.Image = img; dgvContract.SelectedRows[0].Cells[0].Value = null; dgvContract.SelectedRows[0].Cells[0].Value = img; } else { MessageBox.Show(@"Sorry, no scanner is available", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (COMException ex) { MessageBox.Show(ex.Message); } }
public Image Scan(DeviceInfo device, PageSize pageSize, ColorDepth colorDepth, Resolution resolution, Orientation orientation, bool setSize = true) { if (device == null) throw new ArgumentException("Device must be specified"); var scanner = device.Connect(); var wiaCommonDialog = new WPFCommonDialog(); var item = scanner.Items[1]; SetupPageSize(item, pageSize, colorDepth, resolution, orientation, setSize); var image = (ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false); string fileName = Path.GetTempFileName(); File.Delete(fileName); image.SaveFile(fileName); image = null; // add file to output list return Image.FromFile(fileName); }
void Scan() { var deviceManager = new DeviceManager(); DeviceInfo AvailableScanner = null; if (cboScanner.GetSelectedDataRow() is ScannerViewModels item) { AvailableScanner = deviceManager.DeviceInfos[item.Id]; var device = AvailableScanner.Connect(); //Connect to the available scanner. var ScanerItem = device.Items[1]; // select the scanner. var imgFile = (ImageFile)ScanerItem.Transfer(); //Retrive an image in Jpg format and store it into a variable. this.Invoke(new Action(() => { this.scanners.ScanImage = Image.FromStream(new MemoryStream((byte[])imgFile.FileData.get_BinaryData())); this.Close(); })); } }
void scan(DeviceInfo device) { if (textBoxFilePath.Text == "") { System.Windows.MessageBox.Show("No path choosen"); } else { Cursor = System.Windows.Input.Cursors.Wait; buttonScan.IsEnabled = false; // Connect to the scanner var deviceConnection = device.Connect(); var scannerItem = deviceConnection.Items[1]; int resolution = 150; int width_pixel = 1250; int height_pixel = 1700; int color_mode = 1; int brightnessPercent = Convert.ToInt16(sliderBrightness.Value); AdjustScannerSettings(scannerItem, resolution, 0, 0, width_pixel, height_pixel, 0, brightnessPercent, color_mode); var imageFile = (ImageFile)scannerItem.Transfer(FormatID.wiaFormatJPEG); string path = textBoxFilePath.Text + "\\scan.jpeg"; if (File.Exists(path)) { File.Delete(path); } // Save image ! imageFile.SaveFile(path); imageScanned.Source = new BitmapImage(new Uri(path)); Cursor = System.Windows.Input.Cursors.Arrow; buttonScan.IsEnabled = true; } }
private void btnScan_Click(object sender, EventArgs e) { if (lstListOfScanner.SelectedItem == null) { MessageBox.Show("No Scanner selected"); return; } else { try { Cursor = Cursors.WaitCursor; AvailableScanner = deviceManager.DeviceInfos[1]; var device = AvailableScanner.Connect(); var ScannerItem = device.Items[1]; var imgFile = (ImageFile)ScannerItem.Transfer(FormatID.wiaFormatJPEG); var Path = @"D:\ScanImg.jpg"; if (File.Exists(Path)) { File.Delete(Path); } imgFile.SaveFile(Path); org.ImageLocation = Path; pictureBoxScan.ImageLocation = Path; } catch (COMException ex) { MessageBox.Show(ex.Message); } finally { Cursor = Cursors.Default; } } }
public Bitmap StartScan() { try { //var path = @"C:\Users\oayman\Desktop\scan02222100.jpeg"; // Create a DeviceManager instance var deviceManager = new DeviceManager(); // Create an empty variable to store the scanner instance DeviceInfo firstScannerAvailable = null; // Loop through the list of devices to choose the first available for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++) { // Skip the device if it's not a scanner if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) { continue; } firstScannerAvailable = deviceManager.DeviceInfos[i]; break; } // Connect to the first available scanner var device = firstScannerAvailable.Connect(); // Select the scanner var scannerItem = device.Items[1]; /** * Set the scanner settings */ int resolution = 400; int width_pixel = 1280; int height_pixel = 750; int color_mode = 2; //int resolution = 300; //int width_pixel = 1015; //int height_pixel = 688; //int color_mode = 1; AdjustScannerSettings(scannerItem, resolution, 0, 0, width_pixel, height_pixel, 10, 5, color_mode); // AdjustScannerSettings(scannerItem, 150, 0, 0, 1250, 1700, 0, 0, 1); // Retrieve a image in JPEG format and store it into a variable var imageFile = (ImageFile)scannerItem.Transfer(FormatID.wiaFormatPNG); var path = ConfigurationManager.AppSettings["ElectorsIDsFolderPath"] + "Photo.png"; //var path = @"C:\Users\oayman\Desktop\scan02222100.jpeg"; if (File.Exists(path)) { File.Delete(path); } // Save image ! imageFile.SaveFile(path); var imageBytes = (byte[])imageFile.FileData.get_BinaryData(); var ms = new MemoryStream(imageBytes); var img = Image.FromStream(ms); GC.Collect(); //scan again if (ScanColorFlag == "true") { deviceManager = new DeviceManager(); // Create an empty variable to store the scanner instance firstScannerAvailable = null; // Loop through the list of devices to choose the first available for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++) { // Skip the device if it's not a scanner if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) { continue; } firstScannerAvailable = deviceManager.DeviceInfos[i]; break; } // Connect to the first available scanner device = firstScannerAvailable.Connect(); // Select the scanner scannerItem = device.Items[1]; /** * Set the scanner settings */ color_mode = 0; //int resolution = 300; AdjustScannerSettings(scannerItem, resolution, 0, 0, width_pixel, height_pixel, 10, 5, color_mode); var imageFile2 = (ImageFile)scannerItem.Transfer(FormatID.wiaFormatPNG); if (File.Exists(pathScanColor)) { File.Delete(pathScanColor); } // Save image ! imageFile2.SaveFile(pathScanColor); } // Save the image in some path with filename return((Bitmap)img); } catch (Exception ex) { MessageBox.Show(ex.Message); return(null); // MessageBox.Show("Check the Scanner cable to be connected."); } }
private void button1_Click(object sender, EventArgs e) { /*DeviceManager deviceManager = new DeviceManagerClass(); * for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++) * { * if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) continue; * textBox1.AppendText(String.Format("{0} = {1}", i, deviceManager.DeviceInfos[i].Properties["Name"].get_Value())); * } * * DeviceInfo deviceInfo = deviceManager.DeviceInfos[1];*/ DeviceInfo deviceInfo = deviceManager.DeviceInfos[cmbScanners.SelectedIndex + 1]; Device device = deviceInfo.Connect(); Item scanner = device.Items[1]; int resolution = int.Parse(cmbResolution.SelectedItem.ToString()); int width_pixel = (int)(A4width * resolution); int height_pixel = (int)(A4height * resolution); //#define WIA_IPA_DATATYPE 4103 // 0x1007 //#define WIA_IPA_DATATYPE_STR L"Data Type" //#define WIA_DATA_THRESHOLD 0 //#define WIA_DATA_DITHER 1 //#define WIA_DATA_GRAYSCALE 2 //#define WIA_DATA_COLOR 3 //#define WIA_DATA_COLOR_THRESHOLD 4 //#define WIA_DATA_COLOR_DITHER 5 // // WIA_IPS_CUR_INTENT flags // WIA_IPS_CUR_INTENT //#define WIA_INTENT_NONE 0x00000000 //#define WIA_INTENT_IMAGE_TYPE_COLOR 0x00000001 //#define WIA_INTENT_IMAGE_TYPE_GRAYSCALE 0x00000002 //#define WIA_INTENT_IMAGE_TYPE_TEXT 0x00000004 //#define WIA_INTENT_IMAGE_TYPE_MASK 0x0000000F //#define WIA_INTENT_MINIMIZE_SIZE 0x00010000 //#define WIA_INTENT_MAXIMIZE_QUALITY 0x00020000 //#define WIA_INTENT_BEST_PREVIEW 0x00040000 //#define WIA_INTENT_SIZE_MASK 0x000F0000 //#define WIA_IPA_DEPTH 4104 // 0x1008 //#define WIA_IPA_DEPTH_STR L"Bits Per Pixel" int WIA_IPS_CUR_INTENT = 0; // WIA_INTENT_NONE int WIA_IPA_DATATYPE = 0; // WIA_DATA_THRESHOLD int WIA_IPA_DEPTH = 0; switch (cmbColor.SelectedIndex) { case 0: // ч-б WIA_IPA_DATATYPE = 0; // WIA_DATA_THRESHOLD WIA_IPS_CUR_INTENT = 4; // WIA_INTENT_IMAGE_TYPE_TEXT WIA_IPA_DEPTH = 1; break; case 1: // серый WIA_IPA_DATATYPE = 2; // WIA_DATA_GRAYSCALE WIA_IPS_CUR_INTENT = 2; // WIA_INTENT_IMAGE_TYPE_GRAYSCALE WIA_IPA_DEPTH = 8; break; case 2: // цвет WIA_IPA_DATATYPE = 3; // WIA_DATA_COLOR WIA_IPS_CUR_INTENT = 1; // WIA_INTENT_IMAGE_TYPE_COLOR WIA_IPA_DEPTH = 24; break; } //Guid WiaImgFmt_JPEG = new Guid(0xb96b3cae, 0x0728, 0x11d3, 0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e); //scanner.Properties["4106"].set_Value(WiaImgFmt_JPEG); //#define WIA_IPA_COMPRESSION 4107 // 0x100b //#define WIA_IPA_COMPRESSION_STR L"Compression" // // WIA_IPA_COMPRESSION constants // //#define WIA_COMPRESSION_NONE 0 //#define WIA_COMPRESSION_BI_RLE4 1 //#define WIA_COMPRESSION_BI_RLE8 2 //#define WIA_COMPRESSION_G3 3 //#define WIA_COMPRESSION_G4 4 //#define WIA_COMPRESSION_JPEG 5 /*for (int i = 0; i <= 5; i++) * { * System.Diagnostics.Debug.WriteLine(i); * try * { * scanner.Properties["4107"].set_Value(i); * } * catch (ArgumentException comerr) * { * System.Diagnostics.Debug.WriteLine(comerr.Message); * } * }*/ // // WIA_DPS_DOCUMENT_HANDLING_SELECT flags // //#define FEEDER 0x001 //#define FLATBED 0x002 //#define DUPLEX 0x004 //#define FRONT_FIRST 0x008 //#define BACK_FIRST 0x010 //#define FRONT_ONLY 0x020 //#define BACK_ONLY 0x040 //#define NEXT_PAGE 0x080 //#define PREFEED 0x100 //#define AUTO_ADVANCE 0x200 //device.Properties["Document Handling Select"].set_Value(5); // 3088 int duplex_mode = 2; // Планшет //device.Properties["3096"].set_Value(1); // WIA_IPS_PAGES Планшет - 1 страница if (chkFeeder.Checked) { //device.Properties["3096"].set_Value(0); // Много страниц if (chkDuplex.Checked) { duplex_mode = 5; // Автоподатчик обе стороны } else { duplex_mode = 1; // Автоподатчик одна сторона } } device.Properties["Document Handling Select"].set_Value(duplex_mode); // Яркость WIA_IPS_BRIGHTNESS 6154 scanner.Properties["6154"].set_Value(trkBrightness.Value); // Контраст WIA_IPS_CONTRAST 6155 scanner.Properties["6155"].set_Value(trkContrast.Value); scanner.Properties["4103"].set_Value(WIA_IPA_DATATYPE); scanner.Properties["4104"].set_Value(WIA_IPA_DEPTH); scanner.Properties["6146"].set_Value(WIA_IPS_CUR_INTENT); scanner.Properties["6147"].set_Value(resolution); scanner.Properties["6148"].set_Value(resolution); scanner.Properties["6151"].set_Value(width_pixel); scanner.Properties["6152"].set_Value(height_pixel); //Type type = scanner.Properties["4107"].GetType; //System.Diagnostics.Debug.WriteLine("4107: " + type.); /*foreach (Property propertyItem in scanner.Properties) * { * if (!propertyItem.IsReadOnly) * { * System.Diagnostics.Debug.WriteLine(String.Format("{0}\t{1}\t{2}", propertyItem.Name, propertyItem.PropertyID, propertyItem.get_Value())); * } * }*/ CommonDialogClass commonDialog = new CommonDialogClass(); WIA.ImageProcess imageProcess = new WIA.ImageProcess(); // use to compress jpeg. imageProcess.Filters.Add(imageProcess.FilterInfos["Convert"].FilterID); imageProcess.Filters[1].Properties["FormatID"].set_Value(FormatID.wiaFormatJPEG); imageProcess.Filters[1].Properties["Quality"].set_Value(trkJpegQuality.Value * 10); ImageFile imageFileFront; ImageFile imageFileBack; try { while (true) { imageFileFront = (ImageFile)commonDialog.ShowTransfer(scanner, FormatID.wiaFormatJPEG, true); //imageFileFront = (ImageFile)scanner.Transfer(FormatID.wiaFormatJPEG); filePathFront = GetFileName(); // Path.GetTempFileName() + ".jpg"; imageProcess.Apply(imageFileFront).SaveFile(filePathFront); //imageFileFront.SaveFile(filePathFront); Marshal.ReleaseComObject(imageFileFront); /*thumb = Image.FromFile(filePathFront).GetThumbnailImage(105, 149, () => false, IntPtr.Zero); * * imageList.Images.Add(thumb); * listView1.Items.Add(Path.GetFileName(filePathFront)); * listView1.Items[count].ImageIndex = count++; * * scanFileNames.Add(filePathFront);*/ AppendFile(filePathFront); if (!chkFeeder.Checked) // Планшет - сканируем только одну страницу { break; } if (chkDuplex.Checked) { imageFileBack = (ImageFile)commonDialog.ShowTransfer(scanner, FormatID.wiaFormatJPEG, true); //imageFileBack = (ImageFile)scanner.Transfer(FormatID.wiaFormatJPEG); filePathBack = GetFileName(); // Path.GetTempFileName() + ".jpg"; imageProcess.Apply(imageFileBack).SaveFile(filePathBack); //imageFileBack.SaveFile(filePathBack); Marshal.ReleaseComObject(imageFileBack); /*thumb = Image.FromFile(filePathBack).GetThumbnailImage(105, 149, () => false, IntPtr.Zero); * * imageList.Images.Add(thumb); * listView1.Items.Add(Path.GetFileName(filePathBack)); * listView1.Items[count].ImageIndex = count++; * * scanFileNames.Add(filePathBack);*/ AppendFile(filePathBack); } } } catch (COMException comerr) { switch ((uint)comerr.ErrorCode) { case 0x80210003: toolStripStatus.Text = "Страницы закончились"; break; case 0x80210006: toolStripStatus.Text = "Сканер занят или не готов"; break; case 0x80210064: toolStripStatus.Text = "Сканирование отменено"; break; case 0x8021000C: toolStripStatus.Text = "Некорректные настройки устройства WIA"; break; case 0x80210005: toolStripStatus.Text = "Устройство выключено"; break; case 0x80210001: toolStripStatus.Text = "Неведомая ошибка"; break; } } finally { //imageFileFront = null; //imageFileBack = null; //thumb = null; } }
static int Main(string[] args) { string usage = "scanimage usage\n\n" + "\t-listscanners (if provided we list, then bail)\n" + "\t-scanner id (default is first in the list)\n" + "\t-x x (0) offset \n" + "\t-y y (0) offst \n" + "\t-width x (1000)\n" + "\t-height y (1518)\n" + "\t-resolution r (150)\n" + "\t-outfile fn (default is scan.jpg)\n" + "\t-help (this message)"; // Configure scanner // comic is 10.125 x 6.625 // at 150dpi, 1003x1518 int resolution = 150; int startLeft = 0; int startTop = 0; int widthPixels = 1000; int heightPixels = 1518; int color_mode = 0; /* 0: rgb, 1: grayscale 2: monochrome, 3: autocolor */ int brightnessPct = 0; int contrastPct = 0; int deviceId = -1; bool err; string path = "scan.jpg"; for (int i = 0; i < args.Length; i++) { switch (args[i]) { case "-help": bail(usage); break; case "-l": // fall thru case "-listscanners": listScanningDevices(); return(0); case "-scanner": err = int.TryParse(args[i + 1], out deviceId); if (!err) { bail(usage); } i++; break; case "-o": case "-outfile": path = args[i + 1]; i++; break; case "-x": err = int.TryParse(args[i + 1], out startLeft); if (!err) { bail(usage); } i++; break; case "-y": err = int.TryParse(args[i + 1], out startTop); if (!err) { bail(usage); } i++; break; case "-w": // fall through case "-width": err = int.TryParse(args[i + 1], out widthPixels); if (!err) { bail(usage); } i++; break; case "-h": // fall through case "-height": err = int.TryParse(args[i + 1], out heightPixels); if (!err) { bail(usage); } i++; break; case "-r": // fall through case "-resolution": err = int.TryParse(args[i + 1], out resolution); if (!err) { bail(usage); } i++; break; default: bail(usage); break; } } // Create a DeviceManager instance var deviceManager = new DeviceManager(); // Create an empty variable to store the scanner instance DeviceInfo targetScanner = null; if (deviceId != -1) { targetScanner = deviceManager.DeviceInfos[deviceId]; } else { // Loop through the list of devices to choose the first available for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++) { // Skip the device if it's not a scanner if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) { continue; } targetScanner = deviceManager.DeviceInfos[i]; break; } } if (targetScanner == null) { Console.WriteLine("Scanner not found"); return(-1); } // Connect to the first available scanner var device = targetScanner.Connect(); // Select the scanner var scannerItem = device.Items[1]; adjustScannerSettings(scannerItem, resolution, startLeft, startTop, widthPixels, heightPixels, brightnessPct, contrastPct, color_mode); Console.WriteLine("Scanning with " + targetScanner.Properties["Name"].get_Value() + " to " + path); Console.WriteLine($" resolution: {resolution} image size: {widthPixels},{heightPixels}"); // Retrieve a image in JPEG format and store it into a variable var imageFile = (ImageFile)scannerItem.Transfer(FormatID.wiaFormatJPEG); // Save the image in some path with filename if (File.Exists(path)) { File.Delete(path); } // Save image ! imageFile.SaveFile(path); return(0); }
public Scanner() { _deviceId = GetDefaultDeviceID(); _deviceInfo = FindDevice(_deviceId); _device = _deviceInfo.Connect(); }
private XImage ScanOne() { XImage ximage = null; try { // find our device (scanner previously selected with commonDialog.ShowSelectDevice) DeviceManager manager = new DeviceManager(); DeviceInfo deviceInfo = null; foreach (DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == _deviceId) { deviceInfo = info; } } if (deviceInfo != null) { Device device = deviceInfo.Connect(); CommonDialog commonDialog = new CommonDialog(); Item item = device.Items[1]; int dpi = 150; // configure item SetItemIntProperty(ref item, 6147, dpi); // 150 dpi SetItemIntProperty(ref item, 6148, dpi); // 150 dpi SetItemIntProperty(ref item, 6151, (int)(dpi * _width)); // scan width SetItemIntProperty(ref item, 6152, (int)(dpi * _height)); // scan height try { SetItemIntProperty(ref item, 6146, 2); // greyscale } catch { Debug.WriteLine("Failed to set greyscale"); } try { SetItemIntProperty(ref item, 4104, 8); // bit depth } catch { Debug.WriteLine("Failed to set bit depth"); } int deviceHandling = _adf ? 1 : 2; // 1 for ADF, 2 for flatbed // configure device SetDeviceIntProperty(ref device, 3088, deviceHandling); int handlingStatus = GetDeviceIntProperty(ref device, 3087); if (handlingStatus == deviceHandling) { ImageFile image = commonDialog.ShowTransfer(item, formatJpeg, true); // save image to a temp file and then load into an XImage string tempPath = System.IO.Path.GetTempFileName(); File.Delete(tempPath); tempPath = System.IO.Path.ChangeExtension(tempPath, "jpg"); image.SaveFile(tempPath); ximage = XImage.FromFile(tempPath); this.PageImages.Add(tempPath); _tempFilesToDelete.Add(tempPath); } } } catch (COMException ex) { ximage = null; // paper empty if ((uint)ex.ErrorCode != 0x80210003) { throw; } } return(ximage); }
/// <summary> /// /// </summary> /// <param name="wiaDevice"></param> /// <param name="source"></param> /// <param name="scanType"></param> /// <param name="quality"></param> /// <param name="resolution"></param> /// <returns></returns> public WiaResult AcquireScan(WiaDevice wiaDevice, DocumentSources source, ScanTypes scanType, ScanQualityTypes quality = ScanQualityTypes.None, int resolution = 150) { if (wiaDevice.Type != WIADeviceTypes.Scanner) { throw new Exception("The selected device is not a scanner."); } var interim = new List <byte[]>(); try { object index = wiaDevice.ManagerIndex; DeviceInfo deviceInfo = _deviceManager.DeviceInfos[index]; Device device = deviceInfo.Connect(); int intentValue = (int)scanType + (int)quality; int documentStatus = 0; device.Properties.SetProperty(WIA_PROPERTIES_WIA_DPS_DOCUMENT_HANDLING_SELECT, source); device.Properties.SetProperty(WIA_IPS_XRES, resolution); device.Properties.SetProperty(WIA_IPS_YRES, resolution); device.Properties.SetProperty(WIA_IPS_CUR_INTENT, intentValue); documentStatus = (int)device.Properties.GetProperty(WIA_PROPERTIES_WIA_DPS_DOCUMENT_HANDLING_STATUS); foreach (Item itm in device.Items) { while ((documentStatus & FEED_READY) == FEED_READY) { //Get item flags var flag = (WiaItemFlag)itm.Properties.GetProperty(4101); //This process can only handle images. Everything else is to be ignored. if ((flag & WiaItemFlag.ImageItemFlag) != WiaItemFlag.ImageItemFlag) { continue; } ImageFile image = (ImageFile)itm.Transfer(); documentStatus = (int)device.Properties.GetProperty(WIA_PROPERTIES_WIA_DPS_DOCUMENT_HANDLING_STATUS); var bytes = image.ToByte(); interim.Add(bytes); if (this.ItemAcquired != null) { this.ItemAcquired(this, new EventArgs()); } } } } catch (COMException cx) { var code = cx.GetWiaErrorCode(); if (code != 3) { throw new WiaException(WiaExtensions.GetErrorCodeDescription(code), code, cx); } } if (this.AcquisitionCompleted != null) { this.AcquisitionCompleted(this, new EventArgs()); } var result = new WiaResult(interim); return(result); }
private void Skanuj() { var deviceManager = new DeviceManager(); DeviceInfo firstScannerAvailable = null; for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++) { if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) { continue; } firstScannerAvailable = deviceManager.DeviceInfos[i]; break; } var device = firstScannerAvailable.Connect(); var scannerItem = device.Items[1]; int resolution = 150; int width_pixel = 1250; int height_pixel = 1700; int color_mode = 1; AdjustScannerSettings(scannerItem, resolution, 0, 0, width_pixel, height_pixel, 0, 0, color_mode); var imageFile = (ImageFile)scannerItem.Transfer(FormatID.wiaFormatJPEG); numer_zlecenia.Text = numer_zlecenia.Text.Replace("\\", "_"); numer_zlecenia.Text = numer_zlecenia.Text.Replace("/", "_"); //numer_zlecenia.Text = numer_zlecenia.Text.ToUpper(); DoEvents(); if (!Directory.Exists("C:\\Users\\USER\\Dysk Google\\Dokumenty\\" + numer_zlecenia.Text)) { Directory.CreateDirectory("C:\\Users\\USER\\Dysk Google\\Dokumenty\\" + numer_zlecenia.Text); } int numer = 1; String co = "inne"; if (protokol.IsChecked == true) { co = "protokol"; } if (oplaty_drogowe.IsChecked == true) { co = "oplaty"; } if (notatki.IsChecked == true) { co = "notatki"; } String sciezka = "Dokumenty"; if (wyjasnienie.IsChecked == true) { sciezka = "Wyjasnienia"; co = "dokument"; } Sprawdzanie: var path = @"C:\\Users\\USER\\Dysk Google\\" + sciezka + "\\" + numer_zlecenia.Text + "\\" + co.ToString() + "_" + numer.ToString() + ".jpeg"; if (File.Exists(path)) { numer++; goto Sprawdzanie; } imageFile.SaveFile(path); MessageBox.Show("Zrobione", "Info"); }
/// <summary> /// Connects to a specific scanner and initializes parameters /// </summary> /// <param name="_myDeviceInfo">selected scanner</param> private void InitScanner(DeviceInfo _myDeviceInfo) { object np = "Name"; ScannerName = (string)_myDeviceInfo.Properties.get_Item(ref np).get_Value(); objScannerPowerManager.InitScannerPowerManager(ScannerName); Enable(); Scanner = _myDeviceInfo.Connect(); wiaItem = Scanner.Items[1]; SelectPicsProperties(ScanningDPI); }
private void scan_button_Click(object sender, EventArgs e) { // Create a DeviceManager instance var deviceManager = new DeviceManager(); // Create an empty variable to store the scanner instance DeviceInfo firstScannerAvailable = null; // Loop through the list of devices to choose the first available for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++) { // Skip the device if it's not a scanner if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) { continue; } firstScannerAvailable = deviceManager.DeviceInfos[i]; break; } // Connect to the first available scanner var device = firstScannerAvailable.Connect(); // Select the scanner var scannerItem = device.Items[1]; // Retrieve a image in JPEG format and store it into a variable var imageFile = (ImageFile)scannerItem.Transfer(FormatID.wiaFormatPNG); // Save the image in some path with filename var path = @"./img/scan.png"; if (File.Exists(path)) { System.GC.Collect(); System.GC.WaitForPendingFinalizers(); File.Delete(path); } // Save image ! imageFile.SaveFile(path); Bitmap imagen = new Bitmap(path); // pictureBox1.Image = (System.Drawing.Image) imagen; //I did this because there was a process using the file , so the image could not be deleted using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { pictureBox1.Image = System.Drawing.Image.FromStream(stream); stream.Dispose(); } Document MyVariable = new Document(); MyVariable.Create(path); MyVariable.OCR(MODI.MiLANGUAGES.miLANG_SPANISH, true, true); MODI.Image image2 = (MODI.Image)MyVariable.Images[0]; Layout layout = image2.Layout; string str = ""; foreach (Word word in layout.Words) { str += word.Text + " "; } richTextBox1.Text = str; fillRegistroForm(str); }