public static string GetScanAsImage() { string imgResult; var dialog = new CommonDialogClass(); try { // نمایش فرم پیشفرض اسکنر var image = dialog.ShowAcquireImage(WiaDeviceType.ScannerDeviceType); // ذخیره تصویر در یک فایل موقت var filename = Path.GetTempFileName(); image.SaveFile(filename); var img = Image.FromFile(filename); // img جهت ارسال سمت کاربر و نمایش در تگ Base64 تبدیل تصویر به imgResult = Convert.ToBase64String(imageToByteArray(img)); } catch (Exception ex) { Console.WriteLine(ex); // از آنجاییه که امکان نمایش خطا وجود ندارد در صورت بروز خطا رشته خالی // بازگردانده میشود که به معنای نبود تصویر میباشد // a base-64 image to test return @"iVBORw0KGgoAAAANSUhEUgAAAD4AAABQCAMAAAB24TZcAAAABGdBTUEAANbY1E9YMgAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAGAUExURdSmeJp2SHlbQIRoSUg2J499a8KebqeHZuGufBEVJPz7+3NWPVxGMduwhPXEktnX1mtROLq7t5WDc2VMNv3LmKB8TMSidMbFxLGlmXlhSMSddpJUL+y8i3VlVqedlOzr6gUIF2lXRLCLY4ZyXLyYaYhtUYiJhJFyU1dBLLiVZnlwZrWRY/Hx8b+2rbySaJh9YqeooDw4NygnKvvJlpyblzksIUhGRryYckc7MPjGlKODX5x8VVA8K+azgM3FvDInHK2JW2ZbUOHh4Xt2cFpaWKeAUM6kel1RRJmUjo5vSrWzrJJ1WFhLQCQmMuK1iJiMgmthWPPCkOm3hEtBOunm5LCNXnJtZquEXmNkYvG+i7Ctq+y5hrWRbKqSeaN/WqmFVYFgQh8aGOa4isWkd8mcby4vONDNy0AwI5h2U19JMxkdLzIuL1JBMjQ3P5Z6Ve6/j93c2+Xi34KAfJ5/Xvj4+O/u7sSKVJd4Wo6QjXE+IeOwfQcNJoBeQ8Gdbf/Mmf///5GX6NEAAAcrSURBVHja3JbpX9pIGMchiWkgEaOBtaGinBLEyopFBeMqtYKI4kGt2lILFsUoXa3WdZcc/dd3JheHAvaz7/Z5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m3DkhJT/Gs6z55lo0abV5wCSL5txL/CMa4PYPUXN+5qwTj68aXwa5MP4Efj/VDA4TW3BV3PQMp7Wlgnfg555mcPFO8RbXMbXv8Oh6pG3J7IRM8bq3Q/zKLFqUQ3GteNYvbepG1XG57O0Qt9Hmd1bOKC1qbZH/zbK78FWzYMJ2aZoXPq7kr8ZvORr+iUSjJzQb/Gpa5l8BBgBZTppAyfsf0wAAAABJRU5ErkJggg=="; } return imgResult; }
private WIA.Item GetScanningProperties(bool showUI, CommonDialogClass wiaCommonDialog, Device WiaDev) { WIA.Items items = null; if (showUI) { try { items = wiaCommonDialog.ShowSelectItems(WiaDev, WiaImageIntent.TextIntent, WiaImageBias.MinimizeSize, false, true, false); } catch (Exception) { } } else { items = WiaDev.Items; } WIA.Item scanningItem = null; if (items != null && items.Count > 0) { scanningItem = items[1] as WIA.Item; } return(scanningItem); }
public void Configuration()//процедура ручной настройки сканера { try { var commonDialog = new CommonDialogClass(); _scanDevice = commonDialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true); if (_scanDevice == null) { return; } var items = commonDialog.ShowSelectItems(_scanDevice); if (items.Count < 1) { return; } _scannerItem = items[1]; SaveProp(_scanDevice.Properties, ref _defaultDeviceProp); SaveConfig();// сохраняем конфигурацию } catch (Exception e) { MessageBox.Show(e.Message, "Интерфейс сканера не доступен"); } }
public static string GetScanAsImage() { string imgResult; var dialog = new CommonDialogClass(); try { // نمایش فرم پیشفرض اسکنر var image = dialog.ShowAcquireImage(WiaDeviceType.ScannerDeviceType); // ذخیره تصویر در یک فایل موقت var filename = Path.GetTempFileName(); image.SaveFile(filename); var img = Image.FromFile(filename); // img جهت ارسال سمت کاربر و نمایش در تگ Base64 تبدیل تصویر به imgResult = Convert.ToBase64String(imageToByteArray(img)); } catch (Exception ex) { Console.WriteLine(ex); // از آنجاییه که امکان نمایش خطا وجود ندارد در صورت بروز خطا رشته خالی // بازگردانده میشود که به معنای نبود تصویر میباشد // a base-64 image to test return (@"iVBORw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IzIuf32y5zduL0VxtwQPWG2vB7QP0OKKVaejOI7L8lP4+S3r+wY+zSZfGPvGPlFlt8FQ3BCPQPYpfOjWs3QHtMVLJqmU0NLe9XVhsBpOwyER0+D1oE534t8Hsn/KctwLokxUgeunD6FwCA2xMGtAPAdhjkr55afwoaksGpHlAKTnWUK9ZIAt15k/U+mK5voSuoI9Vre/fZPOBcFQKg4+PXsXg7urVra0Stvqmud4mTp4hN/s+lAIy8ErIC7Oz8aITzqegYkUL4tawQ+ivEvudP7Gt6SPpCpewJ8BfN+pb/aq71dG2kjayLuJ3/vC+gB+EBe9Xm/8KEQs67hShMmgIRsNylFuFe9UL1IGHXHNAtr77ZYN7htNB8LxJmCnyaBZULpJ6/g4ZZQCX83FAS1u3675xnTaX/GKFdLl+gIaDZeFpU78rS9oDnzZEmHstqPJKc9n90LJPThyBUZIVRtMv8Q1v9Xx8bzxigddWo1t7yZ//zgSCwRiK6CO0PUD2OR4hMnhHfiPtYiJr4a8Jj4MbHNe7UC4RtTfc5wsd+DD6RbxxTZ8chtkrcJGIlqX41GqTVzFp3wmfmCNi5rNT74Z3nwHi2BjZW11AtdzgvxIfSBl4l/Klzr+bfLvzSNYA1u9xTfmz8f4lLmA5HWfgV8eTa7BEohxox1xeZ1F5Ef4fTrYnL4oGjb7QZ3JVgk2W4KJPMZvmWbo9KWJ27QsXKHm3DkhJT/Gs6z55lo0abV5wCSL5txL/CMa4PYPUXN+5qwTj68aXwa5MP4Efj/VDA4TW3BV3PQMp7Wlgnfg555mcPFO8RbXMbXv8Oh6pG3J7IRM8bq3Q/zKLFqUQ3GteNYvbepG1XG57O0Qt9Hmd1bOKC1qbZH/zbK78FWzYMJ2aZoXPq7kr8ZvORr+iUSjJzQb/Gpa5l8BBgBZTppAyfsf0wAAAABJRU5ErkJggg=="); } return(imgResult); }
/// <summary> /// 扫描 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnScan_Click(object sender, EventArgs e) { //测试并行任务 var tasks = new List <Func <Double> > { test1, test1, test1, test2, test2 }; var x = new Stopwatch(); var query = from t in tasks.AsParallel() select t(); x.Start(); var requst = query.Max(); x.Stop(); richTextBox1.Text = string.Format(@"执行{0}个并发计算,用时 {1:0} 毫秒", tasks.Count, x.Elapsed.TotalMilliseconds); //测试打印机扫描图片 ImageFile imageFile = null; CommonDialogClass cdc = new CommonDialogClass(); try { imageFile = cdc.ShowAcquireImage(WiaDeviceType.ScannerDeviceType, WiaImageIntent.TextIntent, WiaImageBias.MaximizeQuality, "{00000000-0000-0000-0000-000000000000}", true, true, false); } catch (Exception ex) { imageFile = null; } if (imageFile != null) { imageFile.SaveFile(@"D:\"); } }
public override bool SelectDevice() { CommonDialogClass wiaCommonDialog = new CommonDialogClass(); Device device = null; try { device = wiaCommonDialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, true); if (device != null) { m_DeviceID = device.DeviceID; FillDeviceData(device); return(true); } else { return(false); } } catch (COMException ex) { if ((WiaScannerError)ex.ErrorCode == WiaScannerError.ScannerNotAvailable) { return(false); } else { WiaScannerException se = BuildScannerException(device, ex); throw se; } } }
public Image ScanImage(ImageFormat outputFormat, string fileName) { if (outputFormat == null) throw new ArgumentNullException("outputFormat"); FileIOPermission filePerm = new FileIOPermission(FileIOPermissionAccess.AllAccess, fileName); filePerm.Demand(); ImageFile imageObject = null; try { if (WiaManager == null) WiaManager = new CommonDialogClass(); imageObject = WiaManager.ShowAcquireImage(WiaDeviceType.ScannerDeviceType, WiaImageIntent.GrayscaleIntent, WiaImageBias.MaximizeQuality, outputFormat.Guid.ToString("B"), false, true, true); imageObject.SaveFile(fileName); return Image.FromFile(fileName); } catch (COMException ex) { string message = "Error scanning image"; throw new WiaOperationException(message, ex); } finally { if (imageObject != null) Marshal.ReleaseComObject(imageObject); } }
public static Item GetItem(Device device, ExtendedScanSettings settings) { Item item; if (settings.UseNativeUI) { try { var items = new CommonDialogClass().ShowSelectItems(device, WiaImageIntent.UnspecifiedIntent, WiaImageBias.MaximizeQuality, true, true, true); item = items[1]; } catch (COMException e) { if ((uint)e.ErrorCode == Errors.UI_CANCELED) { return(null); } throw; } } else { item = device.Items[1]; } return(item); }
/// <summary> /// Gets the device that will be used to acquire an image. /// </summary> private static WiaResult GetDevice(out Device device) { device = null; try { CommonDialogClass cdc = new CommonDialogClass(); device = cdc.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, false, false); if (device == null) //Either the user cancelled OR we have no device we can use to get an image. { return(new WiaResult(string.Format(ERROR_MESSAGE_FORMAT, "get the capture device", "No device was selected"))); } else { return(WiaResult.Success); } } catch (COMException ce) { if (logger.IsDebugEnabled) { logger.Debug(WiaConstants.LoggingConstants.ExceptionOccurred, ce); } return(new WiaResult(string.Format(ERROR_MESSAGE_FORMAT, "get the capture device", WiaError.GetErrorMessage(ce)))); } }
/// <summary> /// Checks to see if WIA is available for use on this machine. /// </summary> public static bool IsWiaAvailable() { if (logger.IsDebugEnabled) { logger.Debug(WiaConstants.LoggingConstants.MethodCalled); } try { //We'll see if the WIA automation library is available by trying to //create an instance of the CommonDialogClass. Internally, the CLR //will be attempting to create an instance of the WIA Automation library. //If this instance is not registered then we'll get COM hand us a //CLASS_NOT_REGISTERED HRESULT which the CLR converts into a COMException for //us. If an exception is thrown then the it means that COM couldn't locate //the automation library so we can't scan using WIA. CommonDialogClass cdc = new CommonDialogClass(); return(true); } catch (COMException) { return(false); } }
public ActionResult Scan(string PatientRegNo, string Email) { string path = ""; CommonDialogClass commonDialogClass = new CommonDialogClass(); //CommonDialogClass commonDialogClass = new CommonDialogClass(); try { string date = AutoGanrateferecnCode(); Device scannerDevice = commonDialogClass.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, false, false); if (scannerDevice != null) { Item scannnerItem = scannerDevice.Items[1]; AdjustScannerSettings(scannnerItem, 200, 0, 0, 1700, 2300, 0, 0); object scanResult = commonDialogClass.ShowTransfer(scannnerItem, WIA.FormatID.wiaFormatPNG, false); if (scanResult != null) { ImageFile image = (ImageFile)scanResult; string fileName = Server.MapPath("~/") + "MRDFiles/" + date + ".JPEG"; SaveImageToPNGFile(image, fileName); path = "/MRDFiles/" + date + ".JPEG"; } } } catch (Exception ex) { throw; } return(new JsonResult { Data = path, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
private byte[] GetImageFromScanner() { byte[] MyImageByte = null; try { const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"; CommonDialogClass wiaDiag = new CommonDialogClass(); ImageFile wiaImage = null; wiaImage = wiaDiag.ShowAcquireImage(WiaDeviceType.ScannerDeviceType, WiaImageIntent.ColorIntent, WiaImageBias.MinimizeSize, wiaFormatJPEG, true, true, false); if (wiaImage == null) { return(null); } Vector vect = wiaImage.FileData; MyImageByte = (byte[])vect.get_BinaryData(); } catch (Exception err) { if (err.Message.IndexOf("0x80210015") != -1) { glb_function.MsgBox("لم يتم التعرف على أي ماسحة ضوئية"); } else { glb_function.MsgBox(err.Message); } } return(MyImageByte); }
private void btnScanNow_Click(object sender, EventArgs e) { try { CommonDialogClass commonDialogClass = new CommonDialogClass(); Device scannerDevice = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false); if (scannerDevice != null) { Item scannnerItem = scannerDevice.Items[1]; AdjustScannerSettings(scannnerItem, (int)nudRes.Value, 0, 0, (int)nudWidth.Value, (int)nudHeight.Value, 0, 0, cmbCMIndex); object scanResult = commonDialogClass.ShowTransfer(scannnerItem, WIA.FormatID.wiaFormatTIFF, false); //picScan.Image = (System.Drawing.Image)scanResult; if (scanResult != null) { ImageFile image = (ImageFile)scanResult; try { System.IO.File.Delete("test.tiff"); } catch (Exception) { } SaveImageToTiff(image, "test.tiff"); pbScan.Image = (Image)Image.FromFile("test.tiff").Clone(); } } } catch (Exception err) { MessageBox.Show("Please check your device connection, device not found." + Environment.NewLine + "Error message:" + err.Message, "Device Not Found!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
public MemoryStream getPictureStream() { MemoryStream ms = new MemoryStream(); ImageFile imageFile = null; CommonDialogClass cdc = new CommonDialogClass(); try { imageFile = cdc.ShowAcquireImage(WIA.WiaDeviceType.ScannerDeviceType, WIA.WiaImageIntent.TextIntent, WIA.WiaImageBias.MaximizeQuality, "{00000000-0000-0000-0000-000000000000}", false, false, false); } catch (System.Runtime.InteropServices.COMException) { MessageBox.Show("没有检测到扫描仪"); imageFile = null; } if (imageFile != null) { var buffer = imageFile.FileData.get_BinaryData() as byte[]; ms.Write(buffer, 0, buffer.Length); } else { ms = null; } return(ms); }
public static ScanDevice PromptForDevice() { var wiaCommonDialog = new CommonDialogClass(); try { Device d = wiaCommonDialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false); if (d == null) { return(null); } return(new ScanDevice(d.DeviceID, GetDeviceName(d.DeviceID))); } catch (COMException e) { if ((uint)e.ErrorCode == Errors.NO_DEVICE_FOUND) { throw new NoDevicesFoundException(); } if ((uint)e.ErrorCode == Errors.OFFLINE) { throw new DeviceOfflineException(); } throw new ScanDriverUnknownException(e); } }
/// <summary> /// Acquire an image through the WIA interface /// </summary> /// <param name="errMsg"></param> /// <returns></returns> public static Bitmap AcquireImage(out string errMsg) { errMsg = "All OK!"; try { const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"; var wiaDiag = new CommonDialogClass(); var wiaImage = wiaDiag.ShowAcquireImage(WiaDeviceType.UnspecifiedDeviceType, WiaImageIntent.GrayscaleIntent, WiaImageBias.MaximizeQuality, wiaFormatJPEG, true, true, false); if (wiaImage == null) { errMsg = "Did not acquire data"; return(null); } var vector = wiaImage.FileData; var img = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData())); if (img is Bitmap) { return(img as Bitmap); } var bmp = new Bitmap(img); return(bmp); } catch (Exception ex) { errMsg = "ScanImage failed : " + ex.Message; Debug.WriteLine(errMsg); return(null); } }
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); }
public void InitScan() { ImageProc imgP = new ImageProc(); CommonDialogClass commonDialogClass = new CommonDialogClass(); DeviceIdCmb.SelectedIndex = DeviceCmb.SelectedIndex; try { if (DeviceCmb.Items.Count == 0) { MessageBox.Show("Please connect a scanner."); } Deskew _deskew = new Deskew(); scanSettings _scanSettings = new scanSettings(); List <System.Drawing.Image> images = null; images = WIAScanner.AutoScan((string)DeviceIdCmb.SelectedItem, Convert.ToInt32(dpiTxt.Text), (Convert.ToDouble(cropxTxt.Text)), (Convert.ToDouble(cropyTxt.Text)), (Convert.ToDouble(widthTxt.Text) * Convert.ToDouble(dpiTxt.Text)), (Convert.ToDouble(heightTxt.Text) * Convert.ToDouble(dpiTxt.Text)), (int)parseSettings("Brightness"), (int)parseSettings("Contrast"), (int)parseSettings("Color Mode")); selRect.Visibility = Visibility.Collapsed; foreach (System.Drawing.Image image in images) { if ((int)parseSettings("Bpp") == 1) { ScanView.Source = ImageProc.setPixelFormat1(ImageProc.ImgToBmpSource(image), PixelFormats.BlackWhite); saveImageAsFile(ImageProc.setPixelFormat2(ImageProc.ImgToBmpSource(image), System.Drawing.Imaging.PixelFormat.Format1bppIndexed)); } if ((int)parseSettings("Bpp") == 8) { BitmapSource img8bit = ImageProc.setPixelFormat1(ImageProc.ImgToBmpSource(image), PixelFormats.Gray8); ScanView.Source = img8bit; saveImageAsFile(ImageProc.BmpSource2Img(img8bit)); } if ((int)parseSettings("Bpp") == 24) { ScanView.Source = ImageProc.setPixelFormat1(ImageProc.ImgToBmpSource(image), PixelFormats.Bgr24); saveImageAsFile(ImageProc.setPixelFormat2(ImageProc.ImgToBmpSource(image), System.Drawing.Imaging.PixelFormat.Format24bppRgb)); } if ((int)parseSettings("Bpp") == 32) { ScanView.Source = ImageProc.setPixelFormat1(ImageProc.ImgToBmpSource(image), PixelFormats.Bgr32); saveImageAsFile(ImageProc.setPixelFormat2(ImageProc.ImgToBmpSource(image), System.Drawing.Imaging.PixelFormat.Format32bppRgb)); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Unexpected Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
private void previewScan() { CommonDialogClass commonDialogClass = new CommonDialogClass(); DeviceIdCmb.SelectedIndex = DeviceCmb.SelectedIndex; try { if (DeviceCmb.Items.Count == 0) { MessageBox.Show("Please connect a scanner."); } List <System.Drawing.Image> images = WIAScanner.preScan((string)DeviceIdCmb.SelectedItem); foreach (System.Drawing.Image img in images) { //ScanView.Source = ImgToBmpSource(img); /*Bitmap bmp = new Bitmap(img); * Grayscale gs_fil = new Grayscale(0.2125, 0.7154, 0.0721); * Bitmap gs_Bmp = gs_fil.Apply(bmp); * DocumentSkewChecker skewCheck = new DocumentSkewChecker(); * double angle = skewCheck.GetSkewAngle(gs_Bmp); * RotateBilinear rotateFilter = new RotateBilinear(-angle); * rotateFilter.FillColor = System.Drawing.Color.White; * Bitmap rotatedImage = rotateFilter.Apply(gs_Bmp); * new ContrastStretch().ApplyInPlace(gs_Bmp); * new Threshold(180).ApplyInPlace(gs_Bmp); * //new Invert().ApplyInPlace(gs_Bmp); * BlobCounter bc = new BlobCounter(); * * bc.FilterBlobs = true; * bc.ProcessImage(gs_Bmp); * System.Drawing.Rectangle[] rects = bc.GetObjectsRectangles();*/ PreView.Source = ImageProc.ImgToBmpSource(img); //gs_Bmp.Save(userProfile + "\\Pictures\\TreshSample1.png", ImageFormat.Png); /* foreach (System.Drawing.Rectangle rect in rects) * { * cropxTxt.Text = (rect.Left).ToString(); * cropyTxt.Text = (rect.Top / 5).ToString(); * heightTxt.Text = (rect.Bottom).ToString(); * widthTxt.Text = (rect.Right / 45).ToString(); * }*/ } } catch (Exception ex) { MessageBox.Show(ex.Message, "Unexpected Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// Use scanner to scan an image (with user selecting the scanner from a dialog). /// </summary> /// <returns>Scanned images.</returns> public static string Scan() { ICommonDialog dialog = new CommonDialogClass(); var device = dialog.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false); if (device != null) { return(Scan(device.DeviceID)); } else { throw new COMException("You must select a device for scanning."); } }
/// <summary> /// Scan a image with JPEG Format /// </summary> /// <returns></returns> public ImageFile ScanJPEG() { // Connect to the device and instruct it to scan // Connect to the device var device = this._deviceInfo.Connect(); // Select the scanner CommonDialogClass dlg = new CommonDialogClass(); var item = device.Items[1]; try { AdjustScannerSettings(item, resolution, 0, 0, width_pixel, height_pixel, 0, 0, color_mode); object scanResult = dlg.ShowTransfer(item, WIA.FormatID.wiaFormatJPEG, true); if (scanResult != null) { var imageFile = (ImageFile)scanResult; // Return the imageFile return(imageFile); } } catch (COMException e) { // Display the exception in the console. Console.WriteLine(e.ToString()); uint errorCode = (uint)e.ErrorCode; // Catch 2 of the most common exceptions if (errorCode == 0x80210006) { MessageBox.Show("扫描仪忙或未准备好"); } else if (errorCode == 0x80210064) { MessageBox.Show("The scanning process has been cancelled."); } else { MessageBox.Show("A non catched error occurred, check the console", "Error", MessageBoxButtons.OK); } } return(new ImageFile()); }
/// <summary> /// Scanear no formato JPEG /// </summary> /// <returns></returns> public ImageFile ScanJPEG() { // Conecte-se ao dispositivo e instrua-o a digitalizar // Conecte-se ao dispositivo var device = this._deviceInfo.Connect(); // Selecione o Scanner CommonDialogClass dlg = new CommonDialogClass(); var item = device.Items[1]; try { AdjustScannerSettings(item, resolution, 0, 0, width_pixel, height_pixel, 0, 0, color_mode); object scanResult = dlg.ShowTransfer(item, WIA.FormatID.wiaFormatJPEG, true); if (scanResult != null) { var imageFile = (ImageFile)scanResult; // Retorna o imageFile return(imageFile); } } catch (COMException e) { // Exibe a mensagem de erro no console Console.WriteLine(e.ToString()); uint errorCode = (uint)e.ErrorCode; // 2 das exceções mais comuns if (errorCode == 0x80210006) { MessageBox.Show("O scanner está ocupado ou indisponível"); } else if (errorCode == 0x80210064) { MessageBox.Show("O processo de digitalização foi cancelado."); } else { MessageBox.Show("Um erro não detectado ocorreu, verifique no console", "Erro", MessageBoxButtons.OK); } } return(new ImageFile()); }
public ADFScan() { CommonDialogClass class1 = new CommonDialogClass(); Device d = class1.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false); if (d != null) { _deviceID = d.DeviceID; } else { //no scanner chosen return; } }
/// <summary> /// Skanowanie obrazu w formacie PNG /// </summary> /// <returns></returns> public ImageFile ScanPNG() { // Wyswietlenie dostepnych urzadzen, // nastepnie wybieramy urzadzenie, // laczymy sie z urzadzeniem, mamy mozliwosc wykonania skanu var device = this._deviceInfo.Connect(); CommonDialogClass dlg = new CommonDialogClass(); var item = device.Items[1]; try { AdjustScannerSettings(item, resolution, 0, 0, width_pixel, height_pixel, 0, 0, color_mode); // ustawienie skanera object scanResult = dlg.ShowTransfer(item, WIA.FormatID.wiaFormatPNG, true); if (scanResult != null) // jesli skan sie wykonal zwroci zeskanowany obraz { var imageFile = (ImageFile)scanResult; // Zwrocenie imageFile return(imageFile); } } catch (COMException e) { // Wyswietlenie komunikatow Console.WriteLine(e.ToString()); uint errorCode = (uint)e.ErrorCode; // Czesto wyswietlane komunikaty if (errorCode == 0x80210006) { MessageBox.Show("The scanner is busy or isn't ready"); } else if (errorCode == 0x80210064) { MessageBox.Show("The scanning process has been cancelled."); } else { MessageBox.Show("A non catched error occurred, check the console", "Error", MessageBoxButtons.OK); } } return(new ImageFile()); }
public static ScanDevice PromptForScanDevice() { var wiaCommonDialog = new CommonDialogClass(); try { Device d = wiaCommonDialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false); if (d == null) { return null; } return new ScanDevice(d.DeviceID, GetDeviceName(d.DeviceID)); } catch (COMException e) { ThrowDeviceError(e); return null; } }
private void button1_Click(object sender, EventArgs e) { dlg = new CommonDialogClass(); oDevice = dlg.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false); try { Scann(); button1.Text = "Image scanned"; OpenFileDialog dlg = new OpenFileDialog(); if (dlg.ShowDialog() == DialogResult.OK) { pictureBox1.Image = Image.FromFile(dlg.FileName); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void ButtonLoadCameraClick(object sender, EventArgs e) { var deviceManager = new DeviceManagerClass(); if (deviceManager.DeviceInfos.Cast<DeviceInfo>().All(p => p.Type != WiaDeviceType.CameraDeviceType)) { MessageBox.Show(CanNotFindAnyDevice); return; } var commonDialog = new CommonDialogClass(); var device = commonDialog.ShowSelectDevice(WiaDeviceType.CameraDeviceType, true); if (device == null) { return; } this.Import(new CameraPhotoProvider(device)); }
private void ButtonDeviceClick(object sender, System.EventArgs e) { DeviceManager deviceManager = new DeviceManagerClass(); if (deviceManager.DeviceInfos.Cast<DeviceInfo>().All(p => p.Type != WiaDeviceType.CameraDeviceType)) { MessageBox.Show(CanNotFindAnyDevice); return; } var commonDialog = new CommonDialogClass(); var device = commonDialog.ShowSelectDevice(WiaDeviceType.CameraDeviceType, true); if (device == null) { return; } this.settings.DeviceId = device.DeviceID; this.UpdateControls(); }
public ImageFile ScanJPEG() { var device = this._deviceInfo.Connect(); CommonDialogClass dlg = new CommonDialogClass(); var item = device.Items[1]; try { AdjustScannerSettings(item, resolution, 0, 0, width_pixel, height_pixel, 0, 0, color_mode); object scanResult = dlg.ShowTransfer(item, WIA.FormatID.wiaFormatJPEG, true); if (scanResult != null) { var imageFile = (ImageFile)scanResult; return(imageFile); } } catch (COMException e) { Console.WriteLine(e.ToString()); uint errorCode = (uint)e.ErrorCode; if (errorCode == 0x80210006) { MessageBox.Show("Skaner jest zajęty lub nie jest gotowy."); } else if (errorCode == 0x80210064) { MessageBox.Show("Anulowano."); } else { MessageBox.Show("Wystąpił błąd.", "Błąd.", MessageBoxButtons.OK); } } return(new ImageFile()); }
private void ScanDoc() { try { CommonDialogClass commonDialogClass = new CommonDialogClass(); Device scannerDevice = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false); if (scannerDevice != null) { Item scannnerItem = scannerDevice.Items[1]; AdjustScannerSettings(scannnerItem, 150, 0, 0, 1250, 1700, 0, 0, 0); object scanResult = commonDialogClass.ShowTransfer(scannnerItem, WIA.FormatID.wiaFormatTIFF, false); //picScan.Image = (System.Drawing.Image)scanResult; if (scanResult != null) { ImageFile image = (ImageFile)scanResult; string fileName = ""; var files = Directory.GetFiles(clsGlobalVariables.ScannerFilesDirectory, "*.tiff"); try { string f = ((files.Max(p1 => Int32.Parse(Path.GetFileNameWithoutExtension(p1)))) + 1).ToString(); fileName = clsGlobalVariables.ScannerFilesDirectory + "\\" + f + ".tiff"; } catch (Exception ex) { clsGlobalFunctions.ErrorLog(ex); //Log Error fileName = clsGlobalVariables.ScannerFilesDirectory + "\\" + "1.tiff"; } SaveImageToTiff(image, fileName); picScan.ImageLocation = fileName; } } } catch (Exception ex) { clsGlobalFunctions.ErrorLog(ex); //Log Error MessageBox.Show("Check the Device Connection \n or \n Change the Scanner Device", "Devic Not Found!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
/// <summary> /// Queries a device for the Wia Item that we will use to do the capture and /// transfer. /// </summary> private static WiaResult GetCaptureItem(Device device, out Item item) { item = null; try { //Show UI. CommonDialogClass cdc = new CommonDialogClass(); Items items = cdc.ShowSelectItems( device, WiaImageIntent.UnspecifiedIntent, WiaImageBias.MaximizeQuality, true, true, false); if (items == null || items.Count == 0) //Cannot obtain an item to acquire the image OR the user cancelled. { return(new WiaResult(string.Format(ERROR_MESSAGE_FORMAT, "get the capture item", "No items were selected to be captured"))); } else { //Wia arrays are 1-based-indexed. 1 here represents the first item. item = items[1]; return(WiaResult.Success); } } catch (COMException ce) { if (logger.IsDebugEnabled) { logger.Debug(WiaConstants.LoggingConstants.ExceptionOccurred, ce); } return(new WiaResult(string.Format(ERROR_MESSAGE_FORMAT, "get the capture item", WiaError.GetErrorMessage(ce)))); } }
public Image ScanImage(ImageFormat outputFormat, string fileName) { if (outputFormat == null) { throw new ArgumentNullException("outputFormat"); } FileIOPermission filePerm = new FileIOPermission(FileIOPermissionAccess.AllAccess, fileName); filePerm.Demand(); ImageFile imageObject = null; try { if (WiaManager == null) { WiaManager = new CommonDialogClass(); } imageObject = WiaManager.ShowAcquireImage(WiaDeviceType.ScannerDeviceType, WiaImageIntent.GrayscaleIntent, WiaImageBias.MaximizeQuality, outputFormat.Guid.ToString("B"), false, true, true); imageObject.SaveFile(fileName); return(Image.FromFile(fileName)); } catch (COMException ex) { string message = "Error scanning image"; throw new WiaOperationException(message, ex); } finally { if (imageObject != null) { Marshal.ReleaseComObject(imageObject); } } }
private void ScanDoc() { try { CommonDialogClass commonDialogClass = new CommonDialogClass(); Device scannerDevice = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false); if (scannerDevice != null) { Item scannnerItem = scannerDevice.Items[1]; AdjustScannerSettings(scannnerItem, (int)nudRes.Value, 0, 0, (int)nudWidth.Value, (int)nudHeight.Value, 0, 0, cmbCMIndex); object scanResult = commonDialogClass.ShowTransfer(scannnerItem, WIA.FormatID.wiaFormatPNG, false); //picScan.Image = (System.Drawing.Image)scanResult; if (scanResult != null) { ImageFile image = (ImageFile)scanResult; string fileName = ""; string foldername = Path.GetFullPath(@"\image\") + DateTime.Now.ToString("yyyyMMdd"); string txtPath = Path.GetFullPath(foldername); var files = Directory.GetFiles(txtPath, "*.PNG"); try { string f = ((files.Max(p1 => Int32.Parse(Path.GetFileNameWithoutExtension(p1)))) + 1).ToString(); fileName = txtPath + "\\" + f + ".PNG"; } catch (Exception ex) { fileName = txtPath + "\\" + "1.PNG"; } SaveImageToPNG(image, fileName); picScan.ImageLocation = fileName; } } } catch (Exception err) { MessageBox.Show("Check the Device Connection \n or \n Change the Scanner Device", "Devic Not Found!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
public static string SelectDeviceUI() { CommonDialogClass WIACommonDialog = new CommonDialogClass(); Device d; try { d = WIACommonDialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false); } catch(System.Runtime.InteropServices.COMException e) { if ((uint)e.ErrorCode == NO_DEVICE_FOUND) { throw new Exceptions.ENoScannerFound(); } else { throw e; } } return d.DeviceID; }
/// <summary> /// Checks to see if WIA is available for use on this machine. /// </summary> public static bool IsWiaAvailable() { if (logger.IsDebugEnabled) { logger.Debug(WiaConstants.LoggingConstants.MethodCalled); } try { //We'll see if the WIA automation library is available by trying to //create an instance of the CommonDialogClass. Internally, the CLR //will be attempting to create an instance of the WIA Automation library. //If this instance is not registered then we'll get COM hand us a //CLASS_NOT_REGISTERED HRESULT which the CLR converts into a COMException for //us. If an exception is thrown then the it means that COM couldn't locate //the automation library so we can't scan using WIA. CommonDialogClass cdc = new CommonDialogClass(); return true; } catch (COMException) { return false; } }
/// <summary> /// Use scanner to scan an image (with user selecting the scanner from a dialog). /// </summary> /// <returns>Scanned images.</returns> public static string Scan() { ICommonDialog dialog = new CommonDialogClass(); var device = dialog.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false); if (device != null) { return Scan(device.DeviceID); } else { throw new COMException("You must select a device for scanning."); } }
private void scanButton_Click(object sender, EventArgs e) { //WIA Reference requires "embed interop types" property set to false const string wiaFormatBMP = FormatID.wiaFormatBMP;// "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"; CommonDialogClass wiaDiag = new CommonDialogClass(); WIA.ImageFile wiaImage = null; wiaImage = wiaDiag.ShowAcquireImage( WiaDeviceType.ScannerDeviceType, WiaImageIntent.GrayscaleIntent, WiaImageBias.MaximizeQuality, wiaFormatBMP, true, true, false); byte[] buffer = (byte[])wiaImage.FileData.get_BinaryData(); MemoryStream ms = new MemoryStream(buffer); Bitmap bmp = new Bitmap(Image.FromStream(ms)); ArrayList codes = new ArrayList(); BarcodeImaging.FullScanPage(ref codes, bmp, 75); //BarcodeImaging.ScanPage(ref codes, bmp, 75, BarcodeImaging.ScanDirection.Horizontal, BarcodeImaging.BarcodeType.All); foreach (string code in codes) if (!lookupTrackingNumber(code)) MessageBox.Show("Tracking number: " + code + "\n not found"); }
/// <summary> /// Use scanner to scan an image (scanner is selected by its unique id). /// </summary> /// <param name="scannerId"></param> /// <returns>Scanned images.</returns> public static string Scan(string scannerId) { var images = new List<Image>(); var hasMorePages = true; while (hasMorePages) { var manager = new DeviceManager(); var device = (from DeviceInfo info in manager.DeviceInfos where info.DeviceID == scannerId select info.Connect()).FirstOrDefault(); if (device == null) { // enumerate available devices var availableDevices = manager.DeviceInfos.Cast<DeviceInfo>().Aggregate("", (current, info) => current + (info.DeviceID + "\n")); // show error with available devices throw new COMException("The device with provided ID could not be found. Available Devices:\n" + availableDevices); } var item = device.Items[1]; // scan image var wiaCommonDialog = new CommonDialogClass(); var image = new ImageFile(); try { image = (ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP); // save to temp file var fileName = Path.GetTempFileName(); File.Delete(fileName); image.SaveFile(fileName); image = null; // add file to output list images.Add(Image.FromFile(fileName)); } catch (COMException ex) { const string message = "Error scanning image"; throw new WiaOperationException(message, ex); } finally { item = null; if (image != null) Marshal.ReleaseComObject(image); Marshal.ReleaseComObject(wiaCommonDialog); //determine if there are any more pages waiting Property documentHandlingSelect = null; Property documentHandlingStatus = null; foreach (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 new ImageToPdf { FitImagesToPage = true, ImageCompressionFormat = ImageFormat.MemoryBmp, PdfPageSize = PageSize.A4 }.ExportToPdfAsBase64String( images ); }
public static ScanDevice PromptForDevice() { var wiaCommonDialog = new CommonDialogClass(); try { Device d = wiaCommonDialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false); if (d == null) { return null; } return new ScanDevice(d.DeviceID, GetDeviceName(d.DeviceID)); } catch (COMException e) { if ((uint)e.ErrorCode == Errors.NO_DEVICE_FOUND) { throw new NoDevicesFoundException(); } if ((uint)e.ErrorCode == Errors.OFFLINE) { throw new DeviceOfflineException(); } throw new ScanDriverUnknownException(e); } }
public static Item GetItem(Device device, ExtendedScanSettings settings) { Item item; if (settings.UseNativeUI) { try { var items = new CommonDialogClass().ShowSelectItems(device, WiaImageIntent.UnspecifiedIntent, WiaImageBias.MaximizeQuality, true, true, true); item = items[1]; } catch (COMException e) { if ((uint)e.ErrorCode == Errors.UI_CANCELED) return null; throw; } } else { item = device.Items[1]; } return item; }
/*private void EnumerateOptions() { foreach (Property prop in device.Properties) { if (!prop.IsReadOnly) { System.Diagnostics.Debug.WriteLine(string.Format("DEV-{0}:{1}={2}", prop.PropertyID, prop.Name, prop.get_Value())); } else { System.Diagnostics.Debug.WriteLine(string.Format("(RO)DEV-{0}:{1}={2}", prop.PropertyID, prop.Name, prop.get_Value())); } } foreach (Property prop in items[1].Properties) { if (!prop.IsReadOnly) { System.Diagnostics.Debug.WriteLine(string.Format("IT-{0}:{1}={2}", prop.PropertyID, prop.Name, prop.get_Value())); } else { System.Diagnostics.Debug.WriteLine(string.Format("(RO)IT-{0}:{1}={2}", prop.PropertyID, prop.Name, prop.get_Value())); } } }*/ public CScannedImage GetImage() { CommonDialogClass WIACommonDialog = new CommonDialogClass(); Image output; Items items = device.Items; if (settings.ShowScanUI) { try { items = WIACommonDialog.ShowSelectItems(device, WiaImageIntent.UnspecifiedIntent, WiaImageBias.MaximizeQuality, true, true, true); } catch (System.Runtime.InteropServices.COMException e) { if ((uint)e.ErrorCode == UI_CANCELED) return null; } } else { setupDevice(); setupItem(items[1]); } try { ImageFile file = (ImageFile)WIACommonDialog.ShowTransfer(items[1],"{94A0E92D-43C0-494E-AC29-FD45948A5221}",false); //ImageFile file = (ImageFile)WIACommonDialog.ShowTransfer(items[1], "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}", false); System.IO.MemoryStream stream = new System.IO.MemoryStream((byte[])file.FileData.get_BinaryData()); output = Image.FromStream(stream); double koef = 1; switch (settings.AfterScanScale) { case CScanSettings.Scale.ONETOONE: koef = 1; break; case CScanSettings.Scale.ONETOTWO: koef = 2; break; case CScanSettings.Scale.ONETOFOUR: koef = 4; break; case CScanSettings.Scale.ONETOEIGHT: koef = 8; break; } double realWidth = output.Width / koef; double realHeight = output.Height / koef; double horizontalRes = output.HorizontalResolution / koef; double verticalRes = output.VerticalResolution / koef; Bitmap result = new Bitmap((int)realWidth, (int)realHeight); Graphics g = Graphics.FromImage((Image)result); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(output, 0, 0, (int)realWidth, (int)realHeight); result.SetResolution((float)horizontalRes, (float)verticalRes); output.Dispose(); return new CScannedImage(result, settings.Depth); } catch (System.Runtime.InteropServices.COMException e) { if ((uint)e.ErrorCode == ERROR_OUT_OF_PAPER) { return null; } else { System.Windows.Forms.MessageBox.Show("General scanning error!", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return null; } } }
void Scan(ScanColor clr, int dpi) { string deviceid; //Choose Scanner CommonDialogClass class1 = new CommonDialogClass(); Device d = class1.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false); if (d != null) { 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 == 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! img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, WIA.FormatID.wiaFormatJPEG, 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); } }
private object ZoomExecute() { try { var commonDialog = new CommonDialogClass(); Device d = commonDialog.ShowSelectDevice(WiaDeviceType.CameraDeviceType, true, false); } catch (Exception x) { if (x.Message.Contains(WiaError.ScannerNotAvailable)) { MessageBox.Show("No compatible device installed"); } } return null; }
public Image GetImage() { CommonDialogClass WIACommonDialog = new CommonDialogClass(); Image output; Items items = device.Items; if (settings.ShowScanUI) { items = WIACommonDialog.ShowSelectItems(device, WiaImageIntent.UnspecifiedIntent, WiaImageBias.MaximizeQuality, true, true, true); } else { setupDevice(); setupItem(items[1]); } foreach (Property prop in device.Properties) { if (!prop.IsReadOnly) { System.Diagnostics.Debug.WriteLine(string.Format("DEV-{0}:{1}={2}", prop.PropertyID, prop.Name, prop.get_Value())); } else { System.Diagnostics.Debug.WriteLine(string.Format("(RO)DEV-{0}:{1}={2}", prop.PropertyID, prop.Name, prop.get_Value())); } } foreach (Property prop in items[1].Properties) { if (!prop.IsReadOnly) { System.Diagnostics.Debug.WriteLine(string.Format("IT-{0}:{1}={2}", prop.PropertyID, prop.Name, prop.get_Value())); } else { System.Diagnostics.Debug.WriteLine(string.Format("(RO)IT-{0}:{1}={2}", prop.PropertyID, prop.Name, prop.get_Value())); } } try { ImageFile file = (ImageFile)WIACommonDialog.ShowTransfer(items[1], "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}", false); System.IO.MemoryStream stream = new System.IO.MemoryStream((byte[])file.FileData.get_BinaryData()); output = Image.FromStream(stream); double koef = 1; switch (settings.AfterScanScale) { case CScanSettings.Scale.ONETOONE: koef = 1; break; case CScanSettings.Scale.ONETOTWO: koef = 2; break; case CScanSettings.Scale.ONETOFOUR: koef = 4; break; case CScanSettings.Scale.ONETOEIGHT: koef = 8; break; } double realWidth = output.Width / koef; double realHeight = output.Height / koef; double horizontalRes = output.HorizontalResolution / koef; double verticalRes = output.VerticalResolution / koef; Bitmap result = new Bitmap((int)realWidth, (int)realHeight); Graphics g = Graphics.FromImage((Image)result); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(output, 0, 0, (int)realWidth, (int)realHeight); result.SetResolution((float)horizontalRes, (float)verticalRes); output = result; } catch (System.Runtime.InteropServices.COMException e) { if ((uint)e.ErrorCode == ERROR_OUT_OF_PAPER) { return null; } else { throw e; } } return output; }
private void ScanDoc() { try { CommonDialogClass commonDialogClass = new CommonDialogClass(); Device scannerDevice = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false); if (scannerDevice != null) { Item scannnerItem = scannerDevice.Items[1]; AdjustScannerSettings(scannnerItem, (int)nudRes.Value, 0, 0, (int)nudWidth.Value, (int)nudHeight.Value, 0, 0, cmbCMIndex); object scanResult = commonDialogClass.ShowTransfer(scannnerItem, WIA.FormatID.wiaFormatTIFF, false); //picScan.Image = (System.Drawing.Image)scanResult; if (scanResult != null) { ImageFile image = (ImageFile)scanResult; string fileName = ""; var files = Directory.GetFiles(txtPath.Text, "*.tiff"); try { string f = ((files.Max(p1 => Int32.Parse(Path.GetFileNameWithoutExtension(p1)))) + 1).ToString(); fileName = txtPath.Text + "\\" + f + ".tiff"; } catch (Exception ex) { fileName = txtPath.Text + "\\" + "1.tiff"; } SaveImageToTiff(image, fileName); picScan.ImageLocation = fileName; } } } catch(Exception err) { MessageBox.Show("Check the Device Connection \n or \n Change the Scanner Device", "Devic Not Found!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
public void InitScan() { ImageProc imgP = new ImageProc(); CommonDialogClass commonDialogClass = new CommonDialogClass(); DeviceIdCmb.SelectedIndex = DeviceCmb.SelectedIndex; try { if (DeviceCmb.Items.Count == 0) { MessageBox.Show("Please connect a scanner."); } Deskew _deskew = new Deskew(); scanSettings _scanSettings = new scanSettings(); List<System.Drawing.Image> images = null; images = WIAScanner.AutoScan((string)DeviceIdCmb.SelectedItem, Convert.ToInt32(dpiTxt.Text), (Convert.ToDouble(cropxTxt.Text)), (Convert.ToDouble(cropyTxt.Text)), (Convert.ToDouble(widthTxt.Text) * Convert.ToDouble(dpiTxt.Text)), (Convert.ToDouble(heightTxt.Text) * Convert.ToDouble(dpiTxt.Text)), (int)parseSettings("Brightness"), (int)parseSettings("Contrast"), (int)parseSettings("Color Mode")); selRect.Visibility = Visibility.Collapsed; foreach (System.Drawing.Image image in images) { if ((int)parseSettings("Bpp") == 1) { ScanView.Source = ImageProc.setPixelFormat1(ImageProc.ImgToBmpSource(image), PixelFormats.BlackWhite); saveImageAsFile(ImageProc.setPixelFormat2(ImageProc.ImgToBmpSource(image), System.Drawing.Imaging.PixelFormat.Format1bppIndexed)); } if ((int)parseSettings("Bpp") == 8) { BitmapSource img8bit = ImageProc.setPixelFormat1(ImageProc.ImgToBmpSource(image), PixelFormats.Gray8); ScanView.Source = img8bit; saveImageAsFile(ImageProc.BmpSource2Img(img8bit)); } if ((int)parseSettings("Bpp") == 24) { ScanView.Source = ImageProc.setPixelFormat1(ImageProc.ImgToBmpSource(image), PixelFormats.Bgr24); saveImageAsFile(ImageProc.setPixelFormat2(ImageProc.ImgToBmpSource(image), System.Drawing.Imaging.PixelFormat.Format24bppRgb)); } if ((int)parseSettings("Bpp") == 32) { ScanView.Source = ImageProc.setPixelFormat1(ImageProc.ImgToBmpSource(image), PixelFormats.Bgr32); saveImageAsFile(ImageProc.setPixelFormat2(ImageProc.ImgToBmpSource(image), System.Drawing.Imaging.PixelFormat.Format32bppRgb)); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Unexpected Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// Gets the device that will be used to acquire an image. /// </summary> private static WiaResult GetDevice(out Device device) { device = null; try { CommonDialogClass cdc = new CommonDialogClass(); device = cdc.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, false, false); if (device == null) //Either the user cancelled OR we have no device we can use to get an image. { return new WiaResult(string.Format(ERROR_MESSAGE_FORMAT, "get the capture device", "No device was selected")); } else { return WiaResult.Success; } } catch (COMException ce) { if (logger.IsDebugEnabled) { logger.Debug(WiaConstants.LoggingConstants.ExceptionOccurred, ce); } return new WiaResult(string.Format(ERROR_MESSAGE_FORMAT, "get the capture device", WiaError.GetErrorMessage(ce))); } }
/// <summary> /// Queries a device for the Wia Item that we will use to do the capture and /// transfer. /// </summary> private static WiaResult GetCaptureItem(Device device, out Item item) { item = null; try { //Show UI. CommonDialogClass cdc = new CommonDialogClass(); Items items = cdc.ShowSelectItems( device, WiaImageIntent.UnspecifiedIntent, WiaImageBias.MaximizeQuality, true, true, false); if (items == null || items.Count == 0) //Cannot obtain an item to acquire the image OR the user cancelled. { return new WiaResult(string.Format(ERROR_MESSAGE_FORMAT, "get the capture item", "No items were selected to be captured")); } else { //Wia arrays are 1-based-indexed. 1 here represents the first item. item = items[1]; return WiaResult.Success; } } catch (COMException ce) { if (logger.IsDebugEnabled) { logger.Debug(WiaConstants.LoggingConstants.ExceptionOccurred, ce); } return new WiaResult(string.Format(ERROR_MESSAGE_FORMAT, "get the capture item", WiaError.GetErrorMessage(ce))); } }
private void previewScan() { CommonDialogClass commonDialogClass = new CommonDialogClass(); DeviceIdCmb.SelectedIndex = DeviceCmb.SelectedIndex; try { if (DeviceCmb.Items.Count == 0) { MessageBox.Show("Please connect a scanner."); } List<System.Drawing.Image> images = WIAScanner.preScan((string)DeviceIdCmb.SelectedItem); foreach (System.Drawing.Image img in images) { //ScanView.Source = ImgToBmpSource(img); /*Bitmap bmp = new Bitmap(img); Grayscale gs_fil = new Grayscale(0.2125, 0.7154, 0.0721); Bitmap gs_Bmp = gs_fil.Apply(bmp); DocumentSkewChecker skewCheck = new DocumentSkewChecker(); double angle = skewCheck.GetSkewAngle(gs_Bmp); RotateBilinear rotateFilter = new RotateBilinear(-angle); rotateFilter.FillColor = System.Drawing.Color.White; Bitmap rotatedImage = rotateFilter.Apply(gs_Bmp); new ContrastStretch().ApplyInPlace(gs_Bmp); new Threshold(180).ApplyInPlace(gs_Bmp); //new Invert().ApplyInPlace(gs_Bmp); BlobCounter bc = new BlobCounter(); bc.FilterBlobs = true; bc.ProcessImage(gs_Bmp); System.Drawing.Rectangle[] rects = bc.GetObjectsRectangles();*/ PreView.Source = ImageProc.ImgToBmpSource(img); //gs_Bmp.Save(userProfile + "\\Pictures\\TreshSample1.png", ImageFormat.Png); /* foreach (System.Drawing.Rectangle rect in rects) { cropxTxt.Text = (rect.Left).ToString(); cropyTxt.Text = (rect.Top / 5).ToString(); heightTxt.Text = (rect.Bottom).ToString(); widthTxt.Text = (rect.Right / 45).ToString(); }*/ } } catch (Exception ex) { MessageBox.Show(ex.Message, "Unexpected Error", MessageBoxButton.OK, MessageBoxImage.Error); } }