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"); }
/// <summary> /// Captura a imagem da câmera digital. /// </summary> /// <param name="imageInfo">Imagem a ser capturada.</param> /// <param name="outputBitmap">Bitmap de saída.</param> /// <returns>True, se foi possível capturar a imagem e false, caso contrário.</returns> public bool GetPicture(WIAImageInfo imageInfo, out Bitmap outputBitmap) { // cria common dialog WIA.CommonDialogClass dlg = new WIA.CommonDialogClass(); bool ret = false; // inicializa bitmap outputBitmap = null; try { // transfere imagem WIA.ImageFile imageFile = (ImageFile)dlg.ShowTransfer(imageInfo.WIAItem, FormatID.wiaFormatJPEG, false); // captura os dados binários da imagem System.IO.MemoryStream memStream = new System.IO.MemoryStream((byte[])imageFile.FileData.get_BinaryData()); // cria bitmap em memória outputBitmap = new Bitmap(memStream); ret = true; } catch { ret = false; } // valor de retorno return(ret); }
public override void AcquireImages(bool showUI) { CommonDialogClass wiaCommonDialog = new CommonDialogClass(); if (m_DeviceID == null) { SelectDevice(); } //Create DeviceManager Device WiaDev = CreateDeviceManager(); WIA.Item scanningItem = GetScanningProperties(showUI, wiaCommonDialog, WiaDev); if (scanningItem == null) { return; } WIA.ImageFile imgFile = null; WIA.Item item = null; PrepareImagesList(); //Start Scan while (HasMorePages(WiaDev)) { item = scanningItem; try { imgFile = ScanImage(wiaCommonDialog, imgFile, item); } catch (COMException ex) { if ((WiaScannerError)ex.ErrorCode == WiaScannerError.PaperEmpty) { break; } else { WiaScannerException se = BuildScannerException(WiaDev, ex); throw se; } } catch (Exception ex) { WiaScannerException se = BuildScannerException(WiaDev, ex); throw se; } finally { item = null; } } }
private WIA.ImageFile ScanImage(CommonDialogClass wiaCommonDialog, WIA.ImageFile imgFile, WIA.Item item) { imgFile = (ImageFile)wiaCommonDialog.ShowTransfer(item, ImageFormat.Tiff.Guid.ToString("B") /* wiaFormatTiff*/, false); byte[] buffer = (byte[])imgFile.FileData.get_BinaryData(); MemoryStream ms = new MemoryStream(buffer); m_ImagesList.Add(Image.FromStream(ms)); imgFile = null; return(imgFile); }
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; }
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); } } }
private void scan(PictureEdit pBox) { WIA.ImageFile img = Scan(); string fileName = Path.GetTempPath() + DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss-fffffff") + ".png"; if (SaveImageToPNGFile(img, fileName)) { btnCam.Enabled = true; btnTake.Enabled = false; DestroyWindow(hWnd); pBox.Image = null; Bitmap bmp = new Bitmap(fileName); pBox.Image = bmp; } }
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); }
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 scan(PictureEdit pBox) { WIA.ImageFile img = null; bool success = Scan(ref img); if (success) { string fname = Path.GetTempPath() + DateTime.Now.ToString("yyyyMMdd-hhmmss-fff") + ".png"; if (SaveImageToPNGFile(img, fname)) { StopCamera(); Bitmap bmp = new Bitmap(fname); pBox.Image = null; pBox.Image = bmp; _filename = fname; } } }
private void goScan() { try { WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false); List <WIA.ImageFile> imageList = new List <ImageFile>(); WIA.Vector vector = image.FileData; Image img = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData())); if (img.Width < img.Height) { img.RotateFlip(RotateFlipType.Rotate90FlipNone); } images.Add(img); return; } catch (Exception) { //throw exc; return; } }
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); }
public Image Start() { WIA.ImageFile wiaImage = null; wiaImage = wiaDiag.ShowAcquireImage( WiaDeviceType.ScannerDeviceType, WiaImageIntent.TextIntent, WiaImageBias.MaximizeQuality, ImageFormat.wiaFormatTIFF, true, true, true ); return(null); if (wiaImage != null) { WIA.Vector vector = wiaImage.FileData; Image image = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData())); wiaImage.SaveFile("d:\\www.jpg"); return(image); } return(null); }
/// <summary> /// Use scanner to scan an image (scanner is selected by its unique id). /// </summary> /// <param name="scannerName"></param> /// <returns>Scanned images.</returns> public static List <Image> Scan(string scannerId) { List <Image> images = new List <Image>(); bool hasMorePages = true; while (hasMorePages) { // select the correct scanner using the provided scannerId parameter WIA.DeviceManager manager = new WIA.DeviceManager(); WIA.Device device = null; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == scannerId) { // connect to scanner device = info.Connect(); break; } } // device was not found if (device == null) { // enumerate available devices string availableDevices = ""; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { availableDevices += info.DeviceID + "\n"; } // show error with available devices throw new Exception("The device with provided ID could not be found. Available Devices:\n" + availableDevices); } WIA.Item item = device.Items[1] as WIA.Item; //AdjustScannerSettings(scannnerItem, (int)nudRes.Value, 0, 0, (int)nudWidth.Value, (int)nudHeight.Value, 0, 0, cmbCMIndex); AdjustScannerSettings(item, 2); try { // scan image WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog(); WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false); // save to temp file string fileName = Path.GetTempFileName(); File.Delete(fileName); image.SaveFile(fileName); image = null; // add file to output list images.Add(Image.FromFile(fileName)); } catch (Exception exc) { throw exc; } finally { item = null; //determine if there are any more pages waiting WIA.Property documentHandlingSelect = null; WIA.Property documentHandlingStatus = null; foreach (WIA.Property prop in device.Properties) { if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT) { documentHandlingSelect = prop; } if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS) { documentHandlingStatus = prop; } } // assume there are no more pages hasMorePages = false; // may not exist on flatbed scanner but required for feeder if (documentHandlingSelect != null) { // check for document feeder if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0) { hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0); } } } } return(images); }
/// <summary> /// Use scanner to scan an image (scanner is selected by its unique id). /// </summary> /// <param name="scannerName"></param> /// <returns>Scanned images path.</returns> public static List <string> Scan(string scannerId, DoWorkEventArgs e) { List <string> images = new List <string>(); bool hasMorePages = true; ITempFilesResource <ImageFile> tempFiles = TempFilesScannerResource <ImageFile> .DefaultInstance(); while (hasMorePages && !e.Cancel) { // select the correct scanner using the provided scannerId parameter WIA.DeviceManager manager = new WIA.DeviceManager(); WIA.Device device = null; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == scannerId) { // connect to scanner device = info.Connect(); break; } } // device was not found if (device == null) { // enumerate available devices string availableDevices = ""; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { availableDevices += info.DeviceID + "\n"; } // show error with available devices throw new Exception("The device with provided ID could not be found. Available Devices:\n" + availableDevices); } WIA.Item item = device.Items[1] as WIA.Item; try { // scan image WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog(); WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false); // save to temp file string fileName = tempFiles.SaveFile(image); image = null; // add file to output list images.Add(fileName); } catch (System.Runtime.InteropServices.COMException exc) { Debug.WriteLine(exc.Message); } catch (Exception exc) { Debug.WriteLine(exc.Message); } finally { item = null; //determine if there are any more pages waiting WIA.Property documentHandlingSelect = null; WIA.Property documentHandlingStatus = null; foreach (WIA.Property prop in device.Properties) { if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT) { documentHandlingSelect = prop; } if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS) { documentHandlingStatus = prop; } } // assume there are no more pages hasMorePages = false; // may not exist on flatbed scanner but required for feeder if (documentHandlingSelect != null) { // check for document feeder if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0) { hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0); } } } } if (!e.Cancel) { return(images); } else { foreach (var image in images) { tempFiles.DeleteFile(image); } images.Clear(); return(images); } }
/// <summary> /// Use scanner to scan an image (scanner is selected by its unique id). /// </summary> /// <param name="scannerName"></param> /// <returns>Scanned images.</returns> public static List <string> Scan(ScanSettings settings) { List <string> images = new List <string>(); bool hasMorePages = true; while (hasMorePages) { // select the correct scanner using the provided scannerId parameter WIA.DeviceManager manager = new WIA.DeviceManager(); WIA.Device device = null; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == settings.DeviceId) { // connect to scanner device = info.Connect(); break; } } // device was not found if (device == null) { // enumerate available devices string availableDevices = ""; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { availableDevices += info.DeviceID + "\n"; } // show error with available devices throw new Exception("The device with provided ID could not be found. Available Devices:\n" + availableDevices); } WIA.Item item = device.Items[1] as WIA.Item; try { // scan image WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog(); WIAScanner.AdjustScannerSettings(item, settings.WIA_Intent); WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false); var imageBytes = (byte[])image.FileData.get_BinaryData(); images.Add(Convert.ToBase64String(imageBytes)); } catch (Exception exc) { throw exc; } finally { item = null; //determine if there are any more pages waiting WIA.Property documentHandlingSelect = null; WIA.Property documentHandlingStatus = null; foreach (WIA.Property prop in device.Properties) { if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT) { documentHandlingSelect = prop; } if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS) { documentHandlingStatus = prop; } } // assume there are no more pages hasMorePages = false; // may not exist on flatbed scanner but required for feeder if (documentHandlingSelect != null) { // check for document feeder if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0) { hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0); } } } } return(images); }
/// <summary> /// Scan Page, /// </summary> /// <param name="wia">Connected Device</param> /// <param name="pageSize">Page Size. A4, A3, A2 Etc</param> /// <param name="RotatePage">Rotation of page while scanning</param> public void Scan(PageSize pageSize, bool rotatePage, int DPI, string filepath, bool useAdf, bool duplex) { int pages = 0; bool hasMorePages = false; WIA.CommonDialog WiaCommonDialog = new WIA.CommonDialog(); try { do { //Connect to Device Device wia = Connect(); WIA.Item item = wia.Items[1] as WIA.Item; //Setup ADF if ((useAdf) || (duplex)) { SetupADF(wia, duplex); } //Setup Page Size SetupPageSize(wia, rotatePage, pageSize, DPI, item); WIA.ImageFile imgFile = null; WIA.ImageFile imgFile_duplex = null; //if duplex is setup, this will be back page imgFile = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false); //If duplex page, get back page now. if (duplex) { imgFile_duplex = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false); } string varImageFileName = filepath + "\\Scanned-" + pages.ToString() + ".jpg"; Delete_File(varImageFileName); //if file already exists. delete it. imgFile.SaveFile(varImageFileName); string varImageFileName_duplex; if (duplex) { varImageFileName_duplex = filepath + "\\Scanned-" + pages++.ToString() + ".jpg"; Delete_File(varImageFileName_duplex); //if file already exists. delete it. imgFile_duplex.SaveFile(varImageFileName); } //Check with scanner to see if there are more pages. if (useAdf || duplex) { hasMorePages = HasMorePages(wia); pages++; @ } } while (hasMorePages); } catch (COMException ex) { } }
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.</returns> public static List <Image> Scan(string scannerId) { List <Image> images = new List <Image>(); bool hasMorePages = true; while (hasMorePages) { // select the correct scanner using the provided scannerId parameter WIA.DeviceManager manager = new WIA.DeviceManager(); WIA.Device device = null; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == scannerId) { // connect to scanner device = info.Connect(); break; } } // device was not found if (device == null) { // enumerate available devices string availableDevices = ""; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { availableDevices += info.DeviceID + "\n"; } // show error with available devices throw new Exception("The device with provided ID could not be found." + "Available Devices:\n" + availableDevices); } // Set color intent to greyscale if user requested it if (clrMode == Utils.ColorMode.Greyscale) { Property prop = device.Items[1].Properties.get_Item("6146"); prop.set_Value(2); //4 is Black-white,gray is 2, color 1 (Color Intent) } WIA.Item item = device.Items[1] as WIA.Item; try { // scan image WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog(); WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false); // save to temp file string fileName = Utils.GetNextFileName(scannedDocumentsPath + "\\NumérisationSansTitre.bmp"); //File.Delete(fileName); image.SaveFile(fileName); image = null; // add file to output list images.Add(Image.FromFile(fileName)); } catch (Exception exc) { throw exc; } finally { item = null; //determine if there are any more pages waiting WIA.Property documentHandlingSelect = null; WIA.Property documentHandlingStatus = null; foreach (WIA.Property prop in device.Properties) { if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT) { documentHandlingSelect = prop; } if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS) { documentHandlingStatus = prop; } } // assume there are no more pages hasMorePages = false; // may not exist on flatbed scanner but required for feeder if (documentHandlingSelect != null) { // check for document feeder if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0) { hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0); } } } } return(images); }
/// <summary> /// Scan Page, /// </summary> /// <param name="wia">Connected Device</param> /// <param name="pageSize">Page Size. A4, A3, A2 Etc</param> /// <param name="RotatePage">Rotation of page while scanning</param> public void Scan(bool rotatePage, int DPI, string filepath, bool useAdf, bool duplex) //PageSize pageSize, { int pages = 0; bool hasMorePages = false; string[] sourceFiles = new string[100]; WIA.CommonDialog WiaCommonDialog = new WIA.CommonDialog(); try { do { // Connect to Device Device wia = Connect(); WIA.Item item = wia.Items[1] as WIA.Item; // Setup ADF if ((useAdf) || (duplex)) { SetupADF(wia, duplex); } // Setup Page Size // SetupPageSize(wia, rotatePage, A4, DPI, item); WIA.ImageFile imgFile = null; WIA.ImageFile imgFile_duplex = null; // if duplex is setup, this will be back page imgFile = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false); // If duplex page, get back page now. if (duplex) { imgFile_duplex = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false); } string varImageFileName = filepath + "\\Scanned" + ".jpeg"; Delete_File(varImageFileName); // if file already exists. delete it. imgFile.SaveFile(varImageFileName); using (var src = new System.Drawing.Bitmap(varImageFileName)) using (var bmp = new System.Drawing.Bitmap(1000, 1000, System.Drawing.Imaging.PixelFormat.Format32bppPArgb)) using (var gr = System.Drawing.Graphics.FromImage(bmp)) { gr.Clear(System.Drawing.Color.Blue); gr.DrawImage(src, new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height)); gr.DrawString("This is vivek", new System.Drawing.Font("Arial", 15, System.Drawing.FontStyle.Regular), System.Drawing.SystemBrushes.WindowText, new System.Drawing.Point(550, 20)); bmp.Save(System.Configuration.ConfigurationSettings.AppSettings["Path"] + "test" + pages + ".jpeg", System.Drawing.Imaging.ImageFormat.Png); ////string imgPath = "test" + pages + ".tiff"; ////sourceFiles[pages] = imgPath; //mergeTiffPages(string str_DestinationPath, string[] sourceFiles) } MergeTiffPages(@"D:\Test\", sourceFiles); string varImageFileName_duplex; if (duplex) { varImageFileName_duplex = filepath + "\\Scanned-" + pages.ToString() + ".tiff"; Delete_File(varImageFileName_duplex); //if file already exists. delete it. imgFile_duplex.SaveFile(varImageFileName); } //Check with scanner to see if there are more pages. if (useAdf || duplex) { hasMorePages = HasMorePages(wia); pages++; } }while (hasMorePages); } catch (System.Runtime.InteropServices.COMException ex) { //throw new System.Exception(CheckError((uint)ex.ErrorCode)); } }
void Scan(ScanColor clr, int dpi) { string deviceid; //Choose Scanner CommonDialog class1 = new CommonDialog(); Device d = class1.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false); if (d != null) { deviceid = d.DeviceID; } else { //no scanner chosen return; } WIA.CommonDialog WiaCommonDialog = new CommonDialog(); bool hasMorePages = true; int x = 0; int numPages = 0; while (hasMorePages) { //Create DeviceManager DeviceManager manager = new DeviceManager(); Device WiaDev = null; foreach (DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == deviceid) { WIA.Properties infoprop = null; infoprop = info.Properties; //connect to scanner WiaDev = info.Connect(); break; } } //Start Scan WIA.ImageFile img = null; WIA.Item Item = WiaDev.Items[1] as WIA.Item; //set properties //BIG SNAG!! if you call WiaDev.Items[1] apprently it erases the item from memory so you cant call it again Item.Properties["6146"].set_Value((int)clr);//Item MUST be stored in a variable THEN the properties must be set. Item.Properties["6147"].set_Value(dpi); Item.Properties["6148"].set_Value(dpi); try {//WATCH OUT THE FORMAT HERE DOES NOT MAKE A DIFFERENCE... .net will load it as a BITMAP! var testFormat = FormatID.wiaFormatJPEG; img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, testFormat, false); //process image: //Save to file and open as .net IMAGE string varImageFileName = Path.GetTempFileName(); if (File.Exists(varImageFileName)) { //file exists, delete it File.Delete(varImageFileName); } img.SaveFile(varImageFileName); Image ret = Image.FromFile(varImageFileName); EventHandler <WiaImageEventArgs> temp = Scanning; if (temp != null) { temp(this, new WiaImageEventArgs(ret)); } numPages++; img = null; } catch (Exception ex) { throw ex; } finally { Item = null; //determine if there are any more pages waiting Property documentHandlingSelect = null; Property documentHandlingStatus = null; foreach (Property prop in WiaDev.Properties) { if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT) { documentHandlingSelect = prop; } if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS) { documentHandlingStatus = prop; } } hasMorePages = false; //assume there are no more pages if (documentHandlingSelect != null) //may not exist on flatbed scanner but required for feeder { //check for document feeder if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0) { hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0); } } x++; } } EventHandler tempCom = ScanComplete; if (tempCom != null) { tempCom(this, EventArgs.Empty); } }
/// <summary> /// /// </summary> /// <param name="scannerId"></param> /// <param name="qualidade"></param> /// <param name="tamanho"></param> /// <param name="tipo"></param> /// <returns></returns> private static List <KeyValuePair <string, Image> > DigitalizaItensEspecifico(string scannerId, WIAScanQuality qualidade, WIAPageSize tamanho, TipoLeituraDocumento tipo) { List <KeyValuePair <string, Image> > images = new List <KeyValuePair <string, Image> >(); //Dictionary<string,Image> images = new Dictionary<string,Image>(); bool hasMorePages = true; WIA.Item item; Mensagens = new HashSet <string>(); // select the correct scanner using the provided scannerId parameter WIA.DeviceManager manager = new WIA.DeviceManager(); WIA.Device device = null; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == scannerId) { device = info.Connect(); //AcquireNormal(device); Dispositivos[scannerId].Propriedades.Clear(); CarregaPropriedades(device, Dispositivos[scannerId].Propriedades); break; } } // device was not found if (device == null) { // enumerate available devices string availableDevices = ""; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { availableDevices += info.DeviceID + "\n"; } // show error with available devices Mensagens.Add("Não foi possível conectar-se ao o dispositivo especificado\n" + availableDevices); } ConfiguraTipoScan(ref device, tipo); item = device.Items[1] as WIA.Item; AjustaPropriedadesDispositivo(item, 0, 0, 0, 0, 1, qualidade, tamanho); WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog(); while (hasMorePages) { try { //Some scanner need WIA_DPS_PAGES to be set to 1, otherwise all pages are acquired but only one is returned as ImageFile GravaPropriedade(ref device, DEVICE_PROPERTY_PAGES_ID, 1); //Scan image WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, WIA.FormatID.wiaFormatPNG, false); if (image != null) { // save to file string fileName = SalvarPNG(image); images.Add(new KeyValuePair <string, Image>(fileName, Image.FromFile(fileName))); } //determine if there are any more pages waiting WIA.Property documentHandlingSelect = null; WIA.Property documentHandlingStatus = null; foreach (WIA.Property prop in device.Properties) { if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT) { documentHandlingSelect = prop; } if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS) { documentHandlingStatus = prop; } } // assume there are no more pages hasMorePages = false; // may not exist on flatbed scanner but required for feeder if (documentHandlingSelect != null) { // check for document feeder if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0) { hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0); } } } catch (Exception exc) { int error = CodigoErroWIA(exc); Mensagens.Add(DescricaoErro(exc)); if (error == WIA_ERROR_PAPER_EMPTY) { hasMorePages = false; } if (error == 0) { throw exc; } } } device = null; return(images); }
private void btncapture_Click(object sender, EventArgs e) { if (treealfresco.SelectedNode == null) { MessageBox.Show("Please select a Space to store your data into", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); //exit btncapture_Click; } if (rdscanner.Checked == true) { Enabled = false; _settings = new ScanSettings() { UseDocumentFeeder = useAdfCheckBox.Checked, ShowTwainUI = useUICheckBox.Checked, Resolution = blackAndWhiteCheckBox.Checked ? ResolutionSettings.Fax : ResolutionSettings.ColourPhotocopier }; try { _twain.StartScanning(_settings); } catch (TwainException ex) { MessageBox.Show(ex.Message); Enabled = true; } } else { WIA.Item item = default(WIA.Item); WIA.CommonDialog WiaCommonDialog = new CommonDialogClass(); try { //Check if the device is scanner or not if (rdscanner.Checked == true) { //scans the image using the Scanner only (ADF or Flatbed) DoScan(); } else { item = SelectedDevice.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture); } } catch (System.Exception ex) { MessageBox.Show("Problem Taking Picture. Please make sure that the camera is plugged in and is not in use by another application. " + "\r\n" + "Extra Info:" + ex.Message, "Problem Grabbing Picture", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); return; } try { //Validate if a image location is selected or not if (treealfresco.SelectedNode == null) { MessageBox.Show("Please select a Space to store your data into", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } ResultSetRowNode node = (ResultSetRowNode)treealfresco.SelectedNode.Tag; LocationUuid = node.id; LocationName = treealfresco.SelectedNode.Text; } catch (Exception ex) { MessageBox.Show(ex.Message); } try { //Executes the device's TakePicture command based on selected image format if (rdjpeg.Checked == true) { string jpegGuid = null; //retrieves jpegKey from registry, used in saving JPEG Microsoft.Win32.RegistryKey jpegKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\{D2923B86-15F1-46FF-A19A-DE825F919576}\\SupportedExtension\\.jpg"); jpegGuid = (string)jpegKey.GetValue("FormatGUID"); //loops through available formats for the captured item, looking for the JPG format foreach (string format in item.Formats) { if ((format == jpegGuid)) { //transfers image to an imagefile object WIA.ImageFile imagefile = (WIA.ImageFile)item.Transfer(format); int Counter = 0; //counter in loop appended to filename bool LoopAgain = true; //searches directory, gets next available picture name while (!(LoopAgain == false)) { string File = SavePath + "\\"; File += txtPrefix.Text; File += Counter; File += ".jpg"; string Filename = txtPrefix.Text; Filename += Counter; Filename += ".jpg"; //if file doesnt exist, save the file if (!System.IO.File.Exists(Filename)) { SavedFilePath = Filename; imagefile.SaveFile(Filename); //saves file to disk //Upload the file to Alfresco UploadNow(Filename, File); MessageBox.Show(File + " uploaded"); LoopAgain = false; } Counter = Counter + 1; } } } } else if (rdgif.Checked == true) { string jpegGuid = null; //retrieves jpegKey from registry, used in saving JPEG Microsoft.Win32.RegistryKey jpegKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\{D2923B86-15F1-46FF-A19A-DE825F919576}\\SupportedExtension\\.jpg"); jpegGuid = (string)jpegKey.GetValue("FormatGUID"); //loops through available formats for the captured item, looking for the JPG format foreach (string format in item.Formats) { if ((format == jpegGuid)) { //transfers image to an imagefile object WIA.ImageFile imagefile = (WIA.ImageFile)item.Transfer(WIA.FormatID.wiaFormatGIF); int Counter = 0; //counter in loop appended to filename bool LoopAgain = true; //searches directory, gets next available picture name while (!(LoopAgain == false)) { string File = SavePath + "\\"; File += txtPrefix.Text; File += Counter; File += ".gif"; string Filename = txtPrefix.Text; Filename += Counter; Filename += ".gif"; //if file doesnt exist, save the file if (!System.IO.File.Exists(Filename)) { SavedFilePath = Filename; imagefile.SaveFile(Filename); //saves file to disk // Upload the file to Alfresco UploadNow(Filename, File); MessageBox.Show(File + " uploaded"); LoopAgain = false; } Counter = Counter + 1; } } } } else if (rdtiff.Checked == true) { string jpegGuid = null; //retrieves jpegKey from registry, used in saving JPEG Microsoft.Win32.RegistryKey jpegKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\{D2923B86-15F1-46FF-A19A-DE825F919576}\\SupportedExtension\\.jpg"); jpegGuid = (string)jpegKey.GetValue("FormatGUID"); //loops through available formats for the captured item, looking for the JPG format foreach (string format in item.Formats) { if ((format == jpegGuid)) { //transfers image to an imagefile object WIA.ImageFile imagefile = (WIA.ImageFile)item.Transfer(WIA.FormatID.wiaFormatTIFF); int Counter = 0; //counter in loop appended to filename bool LoopAgain = true; //searches directory, gets next available picture name while (!(LoopAgain == false)) { string File = SavePath + "\\"; File += txtPrefix.Text; File += Counter; File += ".tiff"; string Filename = txtPrefix.Text; Filename += Counter; Filename += ".tiff"; //if file doesnt exist, save the file if (!System.IO.File.Exists(Filename)) { SavedFilePath = Filename; imagefile.SaveFile(Filename); //saves file to disk UploadNow(Filename, File); MessageBox.Show(File + " uploaded"); LoopAgain = false; } Counter = Counter + 1; } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
public static Image ScanFile(string folderName, string fileName, ImageFormat imageFormat, bool overrideIfExists, ref string savedPath, ref string errorMessage) { WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog(); Device device = ConnectToScanner(GetScannerDevice()); if (device == null) { return(null); } Image scannedImage = null; try { WIA.ImageFile image = null; WIA.Item item = device.Items[1] as WIA.Item; switch (imageFormat) { case ImageFormat.JPEG: image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, JPEGFormat); break; case ImageFormat.PNG: image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, PNGFormat); break; } if (image != null) { string path = FileManager.GetServerDirectoryPath(DB_ServerDirectory.ScanDirectory); string fullPath = ""; string serverDirectorBaseFile = FileManager.GetServerDirectoryName(DB_ServerDirectory.ScanDirectory); if (!Directory.Exists(Path.Combine(path, serverDirectorBaseFile))) { Directory.CreateDirectory(Path.Combine(path, serverDirectorBaseFile)); } if (!Directory.Exists(Path.Combine(Path.Combine(path, serverDirectorBaseFile), folderName))) { Directory.CreateDirectory(Path.Combine(Path.Combine(path, serverDirectorBaseFile), folderName)); } switch (imageFormat) { case ImageFormat.JPEG: fullPath = Path.Combine(Path.Combine(Path.Combine(path, serverDirectorBaseFile), folderName), fileName + ".jpg"); break; case ImageFormat.PNG: fullPath = Path.Combine(Path.Combine(Path.Combine(path, serverDirectorBaseFile), folderName), fileName + ".png"); break; } if (File.Exists(Path.GetFullPath(fullPath))) { if (overrideIfExists) { File.Delete(Path.GetFullPath(fullPath)); } else { errorMessage = "File is already exists"; return(null); } } try { image.SaveFile(Path.GetFullPath(fullPath)); } catch (Exception e) { errorMessage = "Network error"; return(null); } savedPath = Path.GetFullPath(fullPath); scannedImage = Image.FromFile(Path.GetFullPath(fullPath)); } } catch (COMException e) { // Convert the error code to UINT uint errorCode = (uint)e.ErrorCode; // See the error codes if (errorCode == 0x80210006) { errorMessage = "The scanner is busy or isn't ready"; } else if (errorCode == 0x80210064) { errorMessage = "The scanning process has been canceled."; } else if (errorCode == 0x8021000C) { errorMessage = "There is an incorrect setting on the WIA device."; } else if (errorCode == 0x80210005) { errorMessage = "The device is offline. Make sure the device is powered on and connected to the PC."; } else if (errorCode == 0x80210001) { errorMessage = "An unknown error has occurred with the WIA device."; } } return(scannedImage); }
private void DoScan() { WIA.Item item = default(WIA.Item); WIA.ImageFile Img = default(WIA.ImageFile); WIA.CommonDialog WiaCommonDialog = new CommonDialogClass(); bool hasMorePages = true; int x = 0; int numPages = 0; string ImgMain = null; string ImgMainName = null; try { if (treealfresco.SelectedNode == null) { MessageBox.Show("Please select a Space to store your data into", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } ResultSetRowNode node = (ResultSetRowNode)treealfresco.SelectedNode.Tag; LocationUuid = node.id; LocationName = treealfresco.SelectedNode.Text; } catch (Exception ex) { MessageBox.Show(ex.Message); } while (hasMorePages) { //Create DeviceManager DeviceManager manager = new DeviceManagerClass(); Device WiaDev = null; foreach (DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == this.DeviceID) { WIA.Properties infoprop = null; infoprop = info.Properties; //connect to scanner WiaDev = info.Connect(); break; // TODO: might not be correct. Was : Exit For } } //Start Scan Img = null; item = WiaDev.Items[1] as WIA.Item; try { Img = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatTIFF, false); //process image: //one would do image processing here //Save to file string jpegGuid = null; //retrieves jpegKey from registry, used in saving JPEG Microsoft.Win32.RegistryKey jpegKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\{D2923B86-15F1-46FF-A19A-DE825F919576}\\SupportedExtension\\.jpg"); jpegGuid = (string)jpegKey.GetValue("FormatGUID"); //loops through available formats for the captured item, looking for the JPG format foreach (string format in item.Formats) { if ((format == jpegGuid)) { //transfers image to an imagefile object Img = (WIA.ImageFile)item.Transfer(WIA.FormatID.wiaFormatTIFF); int Counter = 0; //counter in loop appended to filename bool LoopAgain = true; //searches directory, gets next available picture name while (!(LoopAgain == false)) { string File = SavePath + "\\"; File += txtPrefix.Text; File += Counter; File += ".tiff"; string Filename = txtPrefix.Text; Filename += Counter; Filename += ".tiff"; if (System.IO.File.Exists(Filename)) { //file exists, delete it System.IO.File.Delete(Filename); } if (numPages == 0) { Img.SaveFile(Filename); } ImgMain = File; ImgMainName = Filename; if (numPages > 0) { int y = Counter; y = Counter - 1; ImgMain = SavePath + "\\"; ImgMain += txtPrefix.Text; ImgMain += y; ImgMain += ".tiff"; ImgMainName = txtPrefix.Text; ImgMainName += y; ImgMainName += ".tiff"; //createtiff(ImgMain, File); } numPages += 1; Counter = Counter + 1; } } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } finally { item = null; //determine if there are any more pages waiting WIA.Property documentHandlingSelect = null; WIA.Property documentHandlingStatus = null; foreach (WIA.Property prop in WiaDev.Properties) { if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT) { documentHandlingSelect = prop; } if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS) { documentHandlingStatus = prop; } } hasMorePages = false; UploadNow(ImgMainName, ImgMain); MessageBox.Show(ImgMain + " uploaded"); //assume there are no more pages if (documentHandlingSelect != null) { //may not exist on flatbed scanner but required for feeder //check for document feeder if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0) { hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0); } } x += 1; } } }
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 = ""; } }
public ArrayList ADFScan() { ArrayList dataArray = new ArrayList(); //Choose Scanner CommonDialogClass class1 = new CommonDialogClass(); // //class1.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false); // Device d = class1.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false); if (d != null) { this.DeviceID = d.DeviceID; } else { //no scanner chosen return(new ArrayList()); } WIA.CommonDialog WiaCommonDialog = new CommonDialogClass(); bool hasMorePages = true; int x = 0; int numPages = 0; while (hasMorePages) { //Create DeviceManager DeviceManager manager = new DeviceManagerClass(); Device WiaDev = null; foreach (DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == this.DeviceID) { WIA.Properties infoprop = null; infoprop = info.Properties; //connect to scanner WiaDev = info.Connect(); break; } } //Start Scan WIA.ImageFile img = null; WIA.Item Item = WiaDev.Items[1] as WIA.Item; try { img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, wiaFormatJPEG, false); //process image: //one would do image processing here // dataArray.Add(img); //Save to file //string varImageFileName = "c:\\test" + x.ToString() + ".jpg"; // if (File.Exists(varImageFileName)) // { // //file exists, delete it // File.Delete(varImageFileName); // } // img.SaveFile(varImageFileName); numPages++; img = null; } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } finally { Item = null; //determine if there are any more pages waiting Property documentHandlingSelect = null; Property documentHandlingStatus = null; foreach (Property prop in WiaDev.Properties) { if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT) { documentHandlingSelect = prop; } if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS) { documentHandlingStatus = prop; } } hasMorePages = false; //assume there are no more pages if (documentHandlingSelect != null) //may not exist on flatbed scanner but required for feeder { //check for document feeder if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0) { hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0); } } x++; } } return(dataArray); }
/// <summary> /// Use scanner to scan an image (scanner is selected by its unique id). /// </summary> /// <param name="scannerName"></param> /// <returns>Scanned images.</returns> public static List <Image> Scan(string scannerId, int pages, WIAScanQuality quality, WIAPageSize pageSize, DocumentSource source) { List <Image> images = new List <Image>(); bool hasMorePages = true; int numbrPages = pages; while (hasMorePages) { // select the correct scanner using the provided scannerId parameter WIA.DeviceManager manager = new WIA.DeviceManager(); WIA.Device device = null; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { if (info.DeviceID == scannerId) { // connect to scanner device = info.Connect(); break; } } // device was not found if (device == null) { // enumerate available devices string availableDevices = ""; foreach (WIA.DeviceInfo info in manager.DeviceInfos) { availableDevices += info.DeviceID + "\n"; } // show error with available devices throw new Exception("The device with provided ID could not be found. Available Devices:\n" + availableDevices); } SetWIAProperty(device.Properties, WIA_DEVICE_PROPERTY_PAGES_ID, 1); SetWIAProperty(device.Properties, WIA_DEVICE_SOURCE_SELECT_ID, source); WIA.Item item = device.Items[1] as WIA.Item; // adjust the scan settings int dpi; int width_pixels; int height_pixels; switch (quality) { case WIAScanQuality.Final: dpi = 300; break; default: throw new Exception("Unknown WIAScanQuality: " + quality.ToString()); } switch (pageSize) { case WIAPageSize.A4: width_pixels = (int)(8.3f * dpi); height_pixels = (int)(11.7f * dpi); break; case WIAPageSize.Letter: width_pixels = (int)(8.5f * dpi); height_pixels = (int)(11f * dpi); break; case WIAPageSize.Legal: width_pixels = (int)(8.5f * dpi); height_pixels = (int)(14f * dpi); break; default: throw new Exception("Unknown WIAPageSize: " + pageSize.ToString()); } AdjustScannerSettings(item, dpi, 0, 0, width_pixels, height_pixels, 0, 0, 1); try { // scan image WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog(); WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false); // save to temp file string fileName = Path.GetTempFileName(); File.Delete(fileName); image.SaveFile(fileName); image = null; // add file to output list images.Add(Image.FromFile(fileName)); } catch (Exception exc) { throw exc; } finally { item = null; //determine if there are any more pages waiting WIA.Property documentHandlingSelect = null; WIA.Property documentHandlingStatus = null; foreach (WIA.Property prop in device.Properties) { if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT) { documentHandlingSelect = prop; } if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS) { documentHandlingStatus = prop; } } // assume there are no more pages hasMorePages = false; // may not exist on flatbed scanner but required for feeder if (documentHandlingSelect != null) { // check for document feeder if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0) { hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0); } } } numbrPages -= 1; if (numbrPages > 0) { hasMorePages = true; } else { hasMorePages = false; } } return(images); }
/// <summary> /// /// </summary> /// <param name="scannerId"></param> /// <param name="qualidade"></param> /// <param name="tamanho"></param> /// <param name="tipo"></param> /// <returns></returns> private static List <KeyValuePair <string, Image> > DigitalizaItens(string scannerId, WIAScanQuality qualidade, WIAPageSize tamanho, TipoLeituraDocumento tipo) { List <KeyValuePair <string, Image> > images = new List <KeyValuePair <string, Image> >(); //Dictionary<string,Image> images = new Dictionary<string,Image>(); bool hasMorePages = true; WIA.Item item; Mensagens = new HashSet <string>(); while (hasMorePages) { // select the correct scanner using the provided scannerId parameter WIA.Device device = LocalizaDispositio(scannerId); try { //SetWIAProperty(device.Properties, WIA_DEVICE_PROPERTY_PAGES_ID, 1); //Escolha da forma de scaneamento, Feeder ou Flatbad ConfiguraTipoScan(ref device, tipo); item = device.Items[1] as WIA.Item; AjustaPropriedadesDispositivo(item, 0, 0, 0, 0, 1, qualidade, tamanho); // scan image WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog(); WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, WIA.FormatID.wiaFormatPNG, false); if (image != null) { // save to file string fileName = SalvarPNG(image); images.Add(new KeyValuePair <string, Image>(fileName, Image.FromFile(fileName))); } //determine if there are any more pages waiting WIA.Property documentHandlingSelect = null; WIA.Property documentHandlingStatus = null; foreach (WIA.Property prop in device.Properties) { if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT) { documentHandlingSelect = prop; } if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS) { documentHandlingStatus = prop; } } // assume there are no more pages hasMorePages = false; // may not exist on flatbed scanner but required for feeder if (documentHandlingSelect != null) { // check for document feeder if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0) { hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0); } } } catch (Exception exc) { int error = CodigoErroWIA(exc); Mensagens.Add(DescricaoErro(exc)); if (error == WIA_ERROR_PAPER_EMPTY) { hasMorePages = false; } if (error == 0) { throw exc; } } finally { item = null; } } return(images); }