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, 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> /// 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); }
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); }
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); } }
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 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; } } }
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); } } }
/// <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) { } }
/// <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)); } }
/// <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); }
public void ADFScan() { //Choose Scanner CommonDialogClass class1 = new CommonDialogClass(); Device d = class1.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false); if (d != null) { this.DeviceID = d.DeviceID; } else { //no scanner chosen return; } 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 // //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++; } } }