private async void btnScan_Click(object sender, EventArgs e) { // prepare the scan profile if (defaultScanProfile == null) { defaultScanProfile = new ScanProfile { Version = ScanProfile.CURRENT_VERSION }; defaultScanProfile.DriverName = "twain"; defaultScanParams = new ScanParams(); var driver = driverFactory.Create(defaultScanProfile.DriverName); driver.ScanProfile = defaultScanProfile; driver.ScanParams = defaultScanParams; var deviceList = driver.GetDeviceList(); if (!deviceList.Any()) { MessageBox.Show("There is no connected device!"); return; } defaultScanProfile.Device = deviceList[0]; } // perfor scan do { await scanPerformer.PerformScan(defaultScanProfile, defaultScanParams, this, notify, ReceiveScannedImage()); } while (MessageBox.Show("Would you like to continue?", "Question", MessageBoxButtons.YesNo) == DialogResult.Yes); SavePDF(imageList.Images); imageList.Delete(Enumerable.Range(0, imageList.Images.Count)); }
private void PerformScan(ScanProfile profile) { OutputVerbose(ConsoleResources.BeginningScan); bool autoSaveEnabled = !appConfigManager.Config.DisableAutoSave && profile.EnableAutoSave && profile.AutoSaveSettings != null; if (options.AutoSave && !autoSaveEnabled) { errorOutput.DisplayError(ConsoleResources.AutoSaveNotEnabled); if (options.OutputPath == null && options.EmailFileName == null) { return; } } IWin32Window parentWindow = new Form { Visible = false }; totalPagesScanned = 0; foreach (int i in Enumerable.Range(1, options.Number)) { if (options.Delay > 0) { OutputVerbose(ConsoleResources.Waiting, options.Delay); Thread.Sleep(options.Delay); } OutputVerbose(ConsoleResources.StartingScan, i, options.Number); pagesScanned = 0; scanPerformer.PerformScan(profile, new ScanParams { NoUI = true, NoAutoSave = !options.AutoSave }, parentWindow, null, ReceiveScannedImage); OutputVerbose(ConsoleResources.PagesScanned, pagesScanned); } }
private bool GetProfile(out ScanProfile profile) { try { if (options.ProfileName == null) { // If no profile is specified, use the default (if there is one) profile = profileManager.Profiles.Single(x => x.IsDefault); } else { // Use the profile with the specified name (case-sensitive) profile = profileManager.Profiles.FirstOrDefault(x => x.DisplayName == options.ProfileName); if (profile == null) { // If none found, try case-insensitive profile = profileManager.Profiles.First(x => x.DisplayName.ToLower() == options.ProfileName.ToLower()); } } } catch (InvalidOperationException) { errorOutput.DisplayError(ConsoleResources.ProfileUnavailableOrAmbiguous); profile = null; return(false); } return(true); }
public static Bitmap PostProcessStep1(Image output, ScanProfile profile) { double scaleFactor = 1; if (!profile.UseNativeUI) { scaleFactor = profile.AfterScanScale.ToIntScaleFactor(); } var result = ImageScaleHelper.ScaleImage(output, scaleFactor); if (!profile.UseNativeUI && profile.ForcePageSize) { float width = output.Width / output.HorizontalResolution; float height = output.Height / output.VerticalResolution; if (float.IsNaN(width) || float.IsNaN(height)) { width = output.Width; height = output.Height; } PageDimensions pageDimensions = profile.PageSize.PageDimensions() ?? profile.CustomPageSize; if (pageDimensions.Width > pageDimensions.Height && width < height) { // Flip dimensions result.SetResolution((float)(output.Width / pageDimensions.HeightInInches()), (float)(output.Height / pageDimensions.WidthInInches())); } else { result.SetResolution((float)(output.Width / pageDimensions.WidthInInches()), (float)(output.Height / pageDimensions.HeightInInches())); } } return result; }
public static Item GetItem(Device device, ScanProfile profile) { Item item; if (profile.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); }
public void PostProcessStep2(ScannedImage image, Bitmap bitmap, ScanProfile profile, ScanParams scanParams, int pageNumber) { if (!profile.UseNativeUI && profile.BrightnessContrastAfterScan) { if (profile.Brightness != 0) { AddTransformAndUpdateThumbnail(image, ref bitmap, new BrightnessTransform { Brightness = profile.Brightness }); } if (profile.Contrast != 0) { AddTransformAndUpdateThumbnail(image, ref bitmap, new TrueContrastTransform { Contrast = profile.Contrast }); } } if (profile.FlipDuplexedPages && pageNumber % 2 == 0) { AddTransformAndUpdateThumbnail(image, ref bitmap, new RotationTransform(RotateFlipType.Rotate180FlipNone)); } if (profile.AutoDeskew) { var op = operationFactory.Create <DeskewOperation>(); if (op.Start(new[] { image })) { operationProgress.ShowProgress(op); } } if (scanParams.DetectPatchCodes && image.PatchCode == PatchCode.None) { image.PatchCode = PatchCodeDetector.Detect(bitmap); } }
public virtual ManagedChannel GetActiveChannel(ScanProfile scanProfile) { foreach (var channel in scanProfile.Channels) { try { logger.LogDebug($"Scanning du channel {channel.Name}."); using var client = new WebClient(); string response = client.DownloadString(channel.TrackerUrl); var tracker = JsonConvert.DeserializeObject <Tracker>(response); if (tracker?.Metadata.First().Tot > 3) { logger.LogInformation($"Le channel {channel.Name} est activé par {tracker?.Metadata.First().Indicatif}"); return(channel); } logger.LogInformation($"Le channel {channel.Name} est inactif."); } catch (Exception e) { logger.LogError($"Erreur lors du scan du channel {channel.Name}.", e); telemetry.TrackException(e, new Dictionary <string, string> { { "ChannelName", channel.Name } }); } } return(null); }
public static Bitmap PostProcessStep1(Image output, ScanProfile profile) { double scaleFactor = 1; if (!profile.UseNativeUI) { scaleFactor = profile.AfterScanScale.ToIntScaleFactor(); } var result = ImageScaleHelper.ScaleImage(output, scaleFactor); if (!profile.UseNativeUI && profile.ForcePageSize) { float width = output.Width / output.HorizontalResolution; float height = output.Height / output.VerticalResolution; if (float.IsNaN(width) || float.IsNaN(height)) { width = output.Width; height = output.Height; } PageDimensions pageDimensions = profile.PageSize.PageDimensions() ?? profile.CustomPageSize; if (pageDimensions.Width > pageDimensions.Height && width < height) { // Flip dimensions result.SetResolution((float)(output.Width / pageDimensions.HeightInInches()), (float)(output.Height / pageDimensions.WidthInInches())); } else { result.SetResolution((float)(output.Width / pageDimensions.WidthInInches()), (float)(output.Height / pageDimensions.HeightInInches())); } } return(result); }
public TwainMessageFilter(ScanProfile settings, Twain tw, FTwainGui form) { this.settings = settings; this.tw = tw; this.form = form; Bitmaps = new List <ScannedImage>(); form.Activated += FTwainGui_Activated; }
public Bitmap PostProcessStep1(Image output, ScanProfile profile, bool supportsNativeUI = true) { double scaleFactor = 1; if (!profile.UseNativeUi || !supportsNativeUI) { scaleFactor = profile.AfterScanScale.ToIntScaleFactor(); } var result = ImageScaleHelper.ScaleImage(output, scaleFactor); if ((profile.UseNativeUi && supportsNativeUI) || (!profile.ForcePageSize && !profile.ForcePageSizeCrop)) { return(result); } var width = output.Width / output.HorizontalResolution; var height = output.Height / output.VerticalResolution; if (float.IsNaN(width) || float.IsNaN(height)) { width = output.Width; height = output.Height; } var pageDimensions = profile.PageSize.PageDimensions() ?? profile.CustomPageSize; if (pageDimensions.Width > pageDimensions.Height && width < height) { if (profile.ForcePageSizeCrop) { result = new CropTransform { Right = (int)((width - (float)pageDimensions.HeightInInches()) * output.HorizontalResolution), Bottom = (int)((height - (float)pageDimensions.WidthInInches()) * output.VerticalResolution) }.Perform(result); } else { result.SafeSetResolution((float)(output.Width / pageDimensions.HeightInInches()), (float)(output.Height / pageDimensions.WidthInInches())); } } else { if (profile.ForcePageSizeCrop) { result = new CropTransform { Right = (int)((width - (float)pageDimensions.WidthInInches()) * output.HorizontalResolution), Bottom = (int)((height - (float)pageDimensions.HeightInInches()) * output.VerticalResolution) }.Perform(result); } else { result.SafeSetResolution((float)(output.Width / pageDimensions.WidthInInches()), (float)(output.Height / pageDimensions.HeightInInches())); } } return(result); }
private void SaveSettings() { if (ScanProfile.IsLocked) { if (!ScanProfile.IsDeviceLocked) { ScanProfile.Device = CurrentDevice; } return; } var pageSize = (PageSizeListItem)cmbPage.SelectedItem; if (ScanProfile.DisplayName != null) { profileNameTracker.RenamingProfile(ScanProfile.DisplayName, txtName.Text); } scanProfile = new ScanProfile { Version = ScanProfile.CURRENT_VERSION, Device = CurrentDevice, IsDefault = isDefault, DriverName = DeviceDriverName, DisplayName = txtName.Text, IconID = iconID, MaxQuality = ScanProfile.MaxQuality, UseNativeUI = rdbNative.Checked, AfterScanScale = (ScanScale)cmbScale.SelectedIndex, BitDepth = (ScanBitDepth)cmbDepth.SelectedIndex, Brightness = trBrightness.Value, Contrast = trContrast.Value, PageAlign = (ScanHorizontalAlign)cmbAlign.SelectedIndex, PageSize = pageSize.Type, CustomPageSizeName = pageSize.CustomName, CustomPageSize = pageSize.CustomDimens, Resolution = (ScanDpi)cmbResolution.SelectedIndex, PaperSource = (ScanSource)cmbSource.SelectedIndex, EnableAutoSave = cbAutoSave.Checked, AutoSaveSettings = ScanProfile.AutoSaveSettings, Quality = ScanProfile.Quality, BrightnessContrastAfterScan = ScanProfile.BrightnessContrastAfterScan, AutoDeskew = ScanProfile.AutoDeskew, WiaOffsetWidth = ScanProfile.WiaOffsetWidth, WiaRetryOnFailure = ScanProfile.WiaRetryOnFailure, WiaDelayBetweenScans = ScanProfile.WiaDelayBetweenScans, WiaDelayBetweenScansSeconds = ScanProfile.WiaDelayBetweenScansSeconds, ForcePageSize = ScanProfile.ForcePageSize, ForcePageSizeCrop = ScanProfile.ForcePageSizeCrop, FlipDuplexedPages = ScanProfile.FlipDuplexedPages, TwainImpl = ScanProfile.TwainImpl, ExcludeBlankPages = ScanProfile.ExcludeBlankPages, BlankPageWhiteThreshold = ScanProfile.BlankPageWhiteThreshold, BlankPageCoverageThreshold = ScanProfile.BlankPageCoverageThreshold }; }
public TwainMessageFilter(ScanProfile settings, Twain tw, FTwainGui form, IScannedImageFactory scannedImageFactory) { this.settings = settings; this.tw = tw; this.form = form; this.scannedImageFactory = scannedImageFactory; Bitmaps = new List<IScannedImage>(); form.Activated += FTwainGui_Activated; }
public static void PostProcessStep2(ScannedImage image, Bitmap bitmap, ScanProfile profile, ScanParams scanParams, int pageNumber) { if (!profile.UseNativeUI && profile.BrightnessContrastAfterScan) { if (profile.Brightness != 0) { AddTransformAndUpdateThumbnail(image, new BrightnessTransform { Brightness = profile.Brightness }); } if (profile.Contrast != 0) { AddTransformAndUpdateThumbnail(image, new TrueContrastTransform { Contrast = profile.Contrast }); } } if (profile.FlipDuplexedPages && pageNumber % 2 == 0) { AddTransformAndUpdateThumbnail(image, new RotationTransform(RotateFlipType.Rotate180FlipNone)); } if (scanParams.DetectPatchCodes && image.PatchCode == PatchCode.None) { IBarcodeReader reader = new BarcodeReader(); var barcodeResult = reader.Decode(bitmap); if (barcodeResult != null) { switch (barcodeResult.Text) { case "PATCH1": image.PatchCode = PatchCode.Patch1; break; case "PATCH2": image.PatchCode = PatchCode.Patch2; break; case "PATCH3": image.PatchCode = PatchCode.Patch3; break; case "PATCH4": image.PatchCode = PatchCode.Patch4; break; case "PATCH6": image.PatchCode = PatchCode.Patch6; break; case "PATCHT": image.PatchCode = PatchCode.PatchT; break; } } } }
public static void Configure(Device device, Item item, ScanProfile profile) { if (profile.UseNativeUI) { return; } ConfigureDeviceProperties(device, profile); ConfigureItemProperties(device, item, profile); }
public WiaBackgroundEventLoop(ScanProfile profile, ScanDevice scanDevice, ThreadFactory threadFactory) { this.profile = profile; this.scanDevice = scanDevice; thread = threadFactory.CreateThread(RunEventLoop); thread.SetApartmentState(ApartmentState.STA); thread.Start(); // Wait for the thread to initialize the background form and event loop initWaiter.WaitOne(); }
public DirectProfileTransfer(ScanProfile profile) { ProcessID = Process.GetCurrentProcess().Id; ScanProfile = profile.Clone(); Locked = ScanProfile.IsLocked; ScanProfile.IsDefault = false; ScanProfile.IsLocked = false; ScanProfile.IsDeviceLocked = false; }
private void AddProfile(ScanProfile profile) { profileManager.Profiles.Add(profile); if (profileManager.Profiles.Count == 1) { profileManager.DefaultProfile = profile; } UpdateProfiles(); SelectProfile(x => x == profile); profileManager.Save(); }
public List <ScanDevice> GetDeviceList(ScanProfile scanProfile) { if (scanProfile.DriverName == ProxiedScanDriver.DRIVER_NAME) { scanProfile.DriverName = scanProfile.ProxyDriverName; } var driver = scanDriverFactory.Create(scanProfile.DriverName); driver.ScanProfile = scanProfile; return(driver.GetDeviceList()); }
public bool Start(ScanProfile scanProfile, ScanDevice scanDevice, ScanParams scanParams, IWin32Window dialogParent, ScannedImageSource.Concrete source) { ScanProfile = scanProfile; ScanDevice = scanDevice; ScanParams = scanParams; DialogParent = dialogParent; ProgressTitle = ScanDevice.Name; Status = new OperationStatus { StatusText = ScanProfile.PaperSource == ScanSource.Glass ? MiscResources.AcquiringData : string.Format(MiscResources.ScanProgressPage, 1), MaxProgress = 1000, ProgressType = OperationProgressType.BarOnly }; // TODO: NoUI // TODO: Test native UI in console behaviour (versus older behaviour) // TODO: What happens if you close FDesktop while a batch scan is in progress? RunAsync(() => { try { try { smoothProgress.Reset(); Scan(source); } catch (WiaException e) { WiaScanErrors.ThrowDeviceError(e); } return(true); } catch (Exception e) { // Don't call InvokeError; the driver will do the actual error handling ScanException = e; return(false); } finally { smoothProgress.Reset(); } }); return(true); }
public async Task <int> Scan(ScanProfile scanProfile, ScanParams scanParams) { if (scanProfile.DriverName == ProxiedScanDriver.DRIVER_NAME) { scanProfile.DriverName = scanProfile.ProxyDriverName; } if (scanProfile.TwainImpl == TwainImpl.Legacy) { scanProfile.TwainImpl = TwainImpl.OldDsm; } scanProfile.UseNativeUi = false; var internalParams = new ScanParams { DetectPatchCodes = scanParams.DetectPatchCodes, NoUi = true, NoAutoSave = true, DoOcr = false, NoThumbnails = true, SkipPostProcessing = true }; var callback = OperationContext.Current.GetCallbackChannel <IScanCallback>(); var pages = 0; await scanPerformer.PerformScan(scanProfile, internalParams, null, null, image => { // TODO: Should stream this // TODO: Also should think about avoiding the intermediate filesystem using (image) { var indexImage = image.RecoveryIndexImage; var imageBytes = File.ReadAllBytes(image.RecoveryFilePath); var sanitizedIndexImage = new RecoveryIndexImage { FileName = Path.GetExtension(indexImage.FileName), TransformList = indexImage.TransformList, BitDepth = indexImage.BitDepth, HighQuality = indexImage.HighQuality }; callback.ImageReceived(imageBytes, sanitizedIndexImage); pages++; } }, cancellation.Token); return(pages); }
public void PostProcessStep2(ScannedImage image, Bitmap bitmap, ScanProfile profile, ScanParams scanParams, int pageNumber, bool supportsNativeUI = true) { if (!scanParams.NoThumbnails) { image.SetThumbnail(thumbnailRenderer.RenderThumbnail(bitmap)); } if (scanParams.SkipPostProcessing) { return; } if (profile.StretchHistogram && !profile.HistogramStretchConfig.IsNull) { AddTransformAndUpdateThumbnail(image, ref bitmap, new StretchHistogramTransform { Parameters = profile.HistogramStretchConfig }); } if ((!profile.UseNativeUI || !supportsNativeUI) && profile.BrightnessContrastAfterScan) { if (profile.Brightness != 0) { AddTransformAndUpdateThumbnail(image, ref bitmap, new BrightnessTransform { Brightness = profile.Brightness }); } if (profile.Contrast != 0) { AddTransformAndUpdateThumbnail(image, ref bitmap, new TrueContrastTransform { Contrast = profile.Contrast }); } } if (profile.FlipDuplexedPages && pageNumber % 2 == 0) { AddTransformAndUpdateThumbnail(image, ref bitmap, new RotationTransform(RotateFlipType.Rotate180FlipNone)); } if (profile.AutoDeskew) { var op = operationFactory.Create <DeskewOperation>(); if (op.Start(new[] { image })) { operationProgress.ShowProgress(op); op.Wait(); } } if (scanParams.DetectPatchCodes && image.PatchCode == PatchCode.None) { image.PatchCode = PatchCodeDetector.Detect(bitmap); } }
public static List<ScannedImage> Scan(ScanProfile settings, ScanDevice device, IWin32Window pForm, IFormFactory formFactory) { var tw = new Twain(); if (!tw.Init(pForm.Handle)) { throw new DeviceNotFoundException(); } if (!tw.SelectByName(device.ID)) { throw new DeviceNotFoundException(); } var form = formFactory.Create<FTwainGui>(); var mf = new TwainMessageFilter(settings, tw, form); form.ShowDialog(pForm); return mf.Bitmaps; }
public async Task TwainScan(ScanDevice scanDevice, ScanProfile scanProfile, ScanParams scanParams, IntPtr hwnd) { try { await Task.Factory.StartNew(() => { var imagePathDict = new Dictionary <ScannedImage, string>(); twainWrapper.Scan(hwnd == IntPtr.Zero ? null : new Win32Window(hwnd), scanDevice, scanProfile, scanParams, twainScanCts.Token, new WorkerImageSource(Callback, imagePathDict), (img, _, path) => imagePathDict.Add(img, path)); }, TaskCreationOptions.LongRunning); } catch (ScanDriverException e) { throw new FaultException <ScanDriverExceptionDetail>(new ScanDriverExceptionDetail(e)); } }
public static List <ScannedImage> Scan(ScanProfile settings, ScanDevice device, IWin32Window pForm, IFormFactory formFactory) { var tw = new Twain(); if (!tw.Init(pForm.Handle)) { throw new DeviceNotFoundException(); } if (!tw.SelectByName(device.ID)) { throw new DeviceNotFoundException(); } var form = formFactory.Create <FTwainGui>(); var mf = new TwainMessageFilter(settings, tw, form); form.ShowDialog(pForm); return(mf.Bitmaps); }
private void UpdateValues(ScanProfile scanProfile) { cbHighQuality.Checked = scanProfile.MaxQuality; tbImageQuality.Value = scanProfile.Quality; txtImageQuality.Text = scanProfile.Quality.ToString("G"); cbBrightnessContrastAfterScan.Checked = scanProfile.BrightnessContrastAfterScan; cbAutoDeskew.Checked = scanProfile.AutoDeskew; cbWiaOffsetWidth.Checked = scanProfile.WiaOffsetWidth; cmbWiaVersion.SelectedIndex = (int)scanProfile.WiaVersion; cbForcePageSize.Checked = scanProfile.ForcePageSize; cbForcePageSizeCrop.Checked = scanProfile.ForcePageSizeCrop; cbFlipDuplex.Checked = scanProfile.FlipDuplexedPages; cmbTwainImpl.SelectedIndex = (int)scanProfile.TwainImpl; cbExcludeBlankPages.Checked = scanProfile.ExcludeBlankPages; tbWhiteThreshold.Value = scanProfile.BlankPageWhiteThreshold; txtWhiteThreshold.Text = scanProfile.BlankPageWhiteThreshold.ToString("G"); tbCoverageThreshold.Value = scanProfile.BlankPageCoverageThreshold; txtCoverageThreshold.Text = scanProfile.BlankPageCoverageThreshold.ToString("G"); }
private void UpdateValues(ScanProfile scanProfile) { cbHighQuality.Checked = scanProfile.MaxQuality; tbImageQuality.Value = scanProfile.Quality; txtImageQuality.Text = scanProfile.Quality.ToString("G"); cbBrightnessContrastAfterScan.Checked = scanProfile.BrightnessContrastAfterScan; cbWiaOffsetWidth.Checked = scanProfile.WiaOffsetWidth; cbForcePageSize.Checked = scanProfile.ForcePageSize; cbFlipDuplex.Checked = scanProfile.FlipDuplexedPages; if (scanProfile.TwainImpl != TwainImpl.X64 || Environment.Is64BitProcess) { cmbTwainImpl.SelectedIndex = (int)scanProfile.TwainImpl; } cbExcludeBlankPages.Checked = scanProfile.ExcludeBlankPages; tbWhiteThreshold.Value = scanProfile.BlankPageWhiteThreshold; txtWhiteThreshold.Text = scanProfile.BlankPageWhiteThreshold.ToString("G"); tbCoverageThreshold.Value = scanProfile.BlankPageCoverageThreshold; txtCoverageThreshold.Text = scanProfile.BlankPageCoverageThreshold.ToString("G"); }
private async Task PerformScan(ScanProfile profile) { OutputVerbose(ConsoleResources.BeginningScan); var autoSaveEnabled = !appConfigManager.Config.DisableAutoSave && profile.EnableAutoSave && profile.AutoSaveSettings != null; if (options.AutoSave && !autoSaveEnabled) { errorOutput.DisplayError(ConsoleResources.AutoSaveNotEnabled); if (options.OutputPath == null && options.EmailFileName == null) { return; } } totalPagesScanned = 0; foreach (var i in Enumerable.Range(1, options.Number)) { if (options.Delay > 0) { OutputVerbose(ConsoleResources.Waiting, options.Delay); Thread.Sleep(options.Delay); } OutputVerbose(ConsoleResources.StartingScan, i, options.Number); pagesScanned = 0; scanList.Add(new List <ScannedImage>()); var scanParams = new ScanParams { NoUi = !options.Progress, NoAutoSave = !options.AutoSave, NoThumbnails = true, DetectPatchCodes = options.SplitPatchT, DoOcr = ocrParams?.LanguageCode != null, OcrParams = ocrParams }; await scanPerformer.PerformScan(profile, scanParams, null, null, ReceiveScannedImage); OutputVerbose(ConsoleResources.PagesScanned, pagesScanned); } }
public void Do() { profile = profileManager.Profiles.First(x => x.DisplayName == Settings.ProfileDisplayName); scanParams = new ScanParams { DetectPatchCodes = Settings.OutputType == BatchOutputType.MultipleFiles && Settings.SaveSeparator == SaveSeparator.PatchT, NoUI = true }; try { Input(); } catch (Exception) { // Save at least some data so it isn't lost Output(); throw; } Output(); }
private static void ConfigureDeviceProperties(Device device, ScanProfile profile) { if (profile.PaperSource != ScanSource.Glass && DeviceSupportsFeeder(device)) { SetDeviceIntProperty(device, 1, DeviceProperties.PAGES); } switch (profile.PaperSource) { case ScanSource.Glass: SetDeviceIntProperty(device, Source.FLATBED, DeviceProperties.PAPER_SOURCE); break; case ScanSource.Feeder: SetDeviceIntProperty(device, Source.FEEDER, DeviceProperties.PAPER_SOURCE); break; case ScanSource.Duplex: SetDeviceIntProperty(device, Source.DUPLEX | Source.FEEDER, DeviceProperties.PAPER_SOURCE); break; } }
public void Scan(IWin32Window dialogParent, ScanDevice scanDevice, ScanProfile scanProfile, ScanParams scanParams, CancellationToken cancelToken, ScannedImageSource.Concrete source, Action <ScannedImage, ScanParams, string> runBackgroundOcr) { try { InternalScan(scanProfile.TwainImpl, dialogParent, scanDevice, scanProfile, scanParams, cancelToken, source, runBackgroundOcr); } catch (DeviceNotFoundException) { if (scanProfile.TwainImpl == TwainImpl.Default) { // Fall back to OldDsm in case of no devices // This is primarily for Citrix support, which requires using twain_32.dll for TWAIN passthrough InternalScan(TwainImpl.OldDsm, dialogParent, scanDevice, scanProfile, scanParams, cancelToken, source, runBackgroundOcr); } else { throw; } } }
public static void Scan(ScanProfile settings, ScanDevice device, IWin32Window pForm, IFormFactory formFactory, ScannedImageSource.Concrete source) { var tw = new Twain(); if (!tw.Init(pForm.Handle)) { throw new DeviceNotFoundException(); } if (!tw.SelectByName(device.ID)) { throw new DeviceNotFoundException(); } var form = formFactory.Create <FTwainGui>(); var mf = new TwainMessageFilter(settings, tw, form); form.ShowDialog(pForm); foreach (var b in mf.Bitmaps) { source.Put(b); } }
public async Task Do() { profile = profileManager.Profiles.First(x => x.DisplayName == Settings.ProfileDisplayName); scanParams = new ScanParams { DetectPatchCodes = Settings.OutputType == BatchOutputType.MultipleFiles && Settings.SaveSeparator == SaveSeparator.PatchT, NoUi = true, DoOcr = Settings.OutputType == BatchOutputType.Load ? (bool?)null // Use the default behaviour if we don't know what will be done with the images : GetSavePathExtension().ToLower() == ".pdf" && ocrManager.DefaultParams?.LanguageCode != null, OcrCancelToken = CancelToken }; try { CancelToken.ThrowIfCancellationRequested(); await Input(); } catch (OperationCanceledException) { return; } catch (Exception) { CancelToken.ThrowIfCancellationRequested(); // Save at least some data so it isn't lost await Output(); throw; } try { CancelToken.ThrowIfCancellationRequested(); await Output(); } catch (OperationCanceledException) { } }
public static void PostProcessStep2(ScannedImage image, ScanProfile profile, int pageNumber) { if (!profile.UseNativeUI && profile.BrightnessContrastAfterScan) { if (profile.Brightness != 0) { AddTransformAndUpdateThumbnail(image, new BrightnessTransform { Brightness = profile.Brightness }); } if (profile.Contrast != 0) { AddTransformAndUpdateThumbnail(image, new TrueContrastTransform { Contrast = profile.Contrast }); } } if (profile.FlipDuplexedPages && pageNumber % 2 == 0) { AddTransformAndUpdateThumbnail(image, new RotationTransform(RotateFlipType.Rotate180FlipNone)); } }
public static void PostProcessStep2(ScannedImage image, ScanProfile profile) { if (!profile.UseNativeUI && profile.BrightnessContrastAfterScan) { if (profile.Brightness != 0) { image.AddTransform(new BrightnessTransform { Brightness = profile.Brightness }); } if (profile.Contrast != 0) { image.AddTransform(new TrueContrastTransform { Contrast = profile.Contrast }); } } }
public List<ScannedImage> Scan(IWin32Window dialogParent, bool activate, ScanDevice scanDevice, ScanProfile scanProfile, ScanParams scanParams) { if (scanProfile.TwainImpl == TwainImpl.Legacy) { return Legacy.TwainApi.Scan(scanProfile, scanDevice, dialogParent, formFactory); } var session = new TwainSession(TwainAppId); var twainForm = formFactory.Create<FTwainGui>(); var images = new List<ScannedImage>(); Exception error = null; bool cancel = false; DataSource ds = null; session.TransferReady += (sender, eventArgs) => { Debug.WriteLine("NAPS2.TW - TransferReady"); if (cancel) { eventArgs.CancelAll = true; } }; session.DataTransferred += (sender, eventArgs) => { Debug.WriteLine("NAPS2.TW - DataTransferred"); using (var output = Image.FromStream(eventArgs.GetNativeImageStream())) { using (var result = ScannedImageHelper.PostProcessStep1(output, scanProfile)) { if (blankDetector.ExcludePage(result, scanProfile)) { return; } var bitDepth = output.PixelFormat == PixelFormat.Format1bppIndexed ? ScanBitDepth.BlackWhite : ScanBitDepth.C24Bit; var image = new ScannedImage(result, bitDepth, scanProfile.MaxQuality, scanProfile.Quality); ScannedImageHelper.PostProcessStep2(image, scanProfile); if (scanParams.DetectPatchCodes) { foreach (var patchCodeInfo in eventArgs.GetExtImageInfo(ExtendedImageInfo.PatchCode)) { if (patchCodeInfo.ReturnCode == ReturnCode.Success) { image.PatchCode = GetPatchCode(patchCodeInfo); } } } images.Add(image); } } }; session.TransferError += (sender, eventArgs) => { Debug.WriteLine("NAPS2.TW - TransferError"); if (eventArgs.Exception != null) { error = eventArgs.Exception; } else if (eventArgs.SourceStatus != null) { Log.Error("TWAIN Transfer Error. Return code = {0}; condition code = {1}; data = {2}.", eventArgs.ReturnCode, eventArgs.SourceStatus.ConditionCode, eventArgs.SourceStatus.Data); } else { Log.Error("TWAIN Transfer Error. Return code = {0}.", eventArgs.ReturnCode); } cancel = true; twainForm.Close(); }; session.SourceDisabled += (sender, eventArgs) => { Debug.WriteLine("NAPS2.TW - SourceDisabled"); twainForm.Close(); }; twainForm.Shown += (sender, eventArgs) => { if (activate) { // TODO: Set this flag based on whether NAPS2 already has focus // http://stackoverflow.com/questions/7162834/determine-if-current-application-is-activated-has-focus // Or maybe http://stackoverflow.com/questions/156046/show-a-form-without-stealing-focus twainForm.Activate(); } Debug.WriteLine("NAPS2.TW - TwainForm.Shown"); try { ReturnCode rc = session.Open(new WindowsFormsMessageLoopHook(dialogParent.Handle)); if (rc != ReturnCode.Success) { Debug.WriteLine("NAPS2.TW - Could not open session - {0}", rc); twainForm.Close(); return; } ds = session.FirstOrDefault(x => x.Name == scanDevice.ID); if (ds == null) { Debug.WriteLine("NAPS2.TW - Could not find DS - DS count = {0}", session.Count()); throw new DeviceNotFoundException(); } rc = ds.Open(); if (rc != ReturnCode.Success) { Debug.WriteLine("NAPS2.TW - Could not open DS - {0}", rc); twainForm.Close(); return; } ConfigureDS(ds, scanProfile, scanParams); var ui = scanProfile.UseNativeUI ? SourceEnableMode.ShowUI : SourceEnableMode.NoUI; Debug.WriteLine("NAPS2.TW - Enabling DS"); rc = ds.Enable(ui, true, twainForm.Handle); Debug.WriteLine("NAPS2.TW - Enable finished"); if (rc != ReturnCode.Success) { Debug.WriteLine("NAPS2.TW - Enable failed - {0}, rc"); twainForm.Close(); } } catch (Exception ex) { Debug.WriteLine("NAPS2.TW - Error"); error = ex; twainForm.Close(); } }; Debug.WriteLine("NAPS2.TW - Showing TwainForm"); twainForm.ShowDialog(dialogParent); Debug.WriteLine("NAPS2.TW - TwainForm closed"); if (ds != null && session.IsSourceOpen) { Debug.WriteLine("NAPS2.TW - Closing DS"); ds.Close(); } if (session.IsDsmOpen) { Debug.WriteLine("NAPS2.TW - Closing session"); session.Close(); } if (error != null) { Debug.WriteLine("NAPS2.TW - Throwing error - {0}", error); if (error is ScanDriverException) { throw error; } throw new ScanDriverUnknownException(error); } return images; }
private void ConfigureDS(DataSource ds, ScanProfile scanProfile, ScanParams scanParams) { if (scanProfile.UseNativeUI) { return; } // Paper Source switch (scanProfile.PaperSource) { case ScanSource.Glass: ds.Capabilities.CapFeederEnabled.SetValue(BoolType.False); ds.Capabilities.CapDuplexEnabled.SetValue(BoolType.False); break; case ScanSource.Feeder: ds.Capabilities.CapFeederEnabled.SetValue(BoolType.True); ds.Capabilities.CapDuplexEnabled.SetValue(BoolType.False); break; case ScanSource.Duplex: ds.Capabilities.CapFeederEnabled.SetValue(BoolType.True); ds.Capabilities.CapDuplexEnabled.SetValue(BoolType.True); break; } // Bit Depth switch (scanProfile.BitDepth) { case ScanBitDepth.C24Bit: ds.Capabilities.ICapPixelType.SetValue(PixelType.RGB); break; case ScanBitDepth.Grayscale: ds.Capabilities.ICapPixelType.SetValue(PixelType.Gray); break; case ScanBitDepth.BlackWhite: ds.Capabilities.ICapPixelType.SetValue(PixelType.BlackWhite); break; } // Page Size, Horizontal Align PageDimensions pageDimensions = scanProfile.PageSize.PageDimensions() ?? scanProfile.CustomPageSize; if (pageDimensions == null) { throw new InvalidOperationException("No page size specified"); } float pageWidth = pageDimensions.WidthInThousandthsOfAnInch() / 1000.0f; float pageHeight = pageDimensions.HeightInThousandthsOfAnInch() / 1000.0f; var pageMaxWidthFixed = ds.Capabilities.ICapPhysicalWidth.GetCurrent(); float pageMaxWidth = pageMaxWidthFixed.Whole + (pageMaxWidthFixed.Fraction / (float)UInt16.MaxValue); float horizontalOffset = 0.0f; if (scanProfile.PageAlign == ScanHorizontalAlign.Center) horizontalOffset = (pageMaxWidth - pageWidth) / 2; else if (scanProfile.PageAlign == ScanHorizontalAlign.Left) horizontalOffset = (pageMaxWidth - pageWidth); ds.Capabilities.ICapUnits.SetValue(Unit.Inches); TWImageLayout imageLayout; ds.DGImage.ImageLayout.Get(out imageLayout); imageLayout.Frame = new TWFrame { Left = horizontalOffset, Right = horizontalOffset + pageWidth, Top = 0, Bottom = pageHeight }; ds.DGImage.ImageLayout.Set(imageLayout); // Brightness, Contrast // Conveniently, the range of values used in settings (-1000 to +1000) is the same range TWAIN supports if (!scanProfile.BrightnessContrastAfterScan) { ds.Capabilities.ICapBrightness.SetValue(scanProfile.Brightness); ds.Capabilities.ICapContrast.SetValue(scanProfile.Contrast); } // Resolution int dpi = scanProfile.Resolution.ToIntDpi(); ds.Capabilities.ICapXResolution.SetValue(dpi); ds.Capabilities.ICapYResolution.SetValue(dpi); // Patch codes if (scanParams.DetectPatchCodes) { ds.Capabilities.ICapPatchCodeDetectionEnabled.SetValue(BoolType.True); } }
public static Item GetItem(Device device, ScanProfile profile) { Item item; if (profile.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; }
public bool ExcludePage(Bitmap bitmap, ScanProfile scanProfile) { return scanProfile.ExcludeBlankPages && IsBlank(bitmap, scanProfile.BlankPageWhiteThreshold, scanProfile.BlankPageCoverageThreshold); }
public void Do() { profile = profileManager.Profiles.First(x => x.DisplayName == Settings.ProfileDisplayName); scanParams = new ScanParams { DetectPatchCodes = Settings.OutputType == BatchOutputType.MultipleFiles && Settings.SaveSeparator == BatchSaveSeparator.PatchT, NoUI = true }; try { Input(); } catch (Exception) { // Save at least some data so it isn't lost Output(); throw; } Output(); }
private static void ConfigureItemProperties(Device device, Item item, ScanProfile profile) { switch (profile.BitDepth) { case ScanBitDepth.Grayscale: SetItemIntProperty(item, 2, ItemProperties.DATA_TYPE); break; case ScanBitDepth.C24Bit: SetItemIntProperty(item, 3, ItemProperties.DATA_TYPE); break; case ScanBitDepth.BlackWhite: SetItemIntProperty(item, 0, ItemProperties.DATA_TYPE); break; } int maxResolution = Math.Min(GetItemIntPropertyMax(item, ItemProperties.VERTICAL_RESOLUTION), GetItemIntPropertyMax(item, ItemProperties.HORIZONTAL_RESOLUTION)); int resolution = Math.Min(profile.Resolution.ToIntDpi(), maxResolution); SetItemIntProperty(item, resolution, ItemProperties.VERTICAL_RESOLUTION); SetItemIntProperty(item, resolution, ItemProperties.HORIZONTAL_RESOLUTION); PageDimensions pageDimensions = profile.PageSize.PageDimensions() ?? profile.CustomPageSize; if (pageDimensions == null) { throw new InvalidOperationException("No page size specified"); } int pageWidth = pageDimensions.WidthInThousandthsOfAnInch() * resolution / 1000; int pageHeight = pageDimensions.HeightInThousandthsOfAnInch() * resolution / 1000; int horizontalSize = GetDeviceIntProperty(device, profile.PaperSource == ScanSource.Glass ? DeviceProperties.HORIZONTAL_BED_SIZE : DeviceProperties.HORIZONTAL_FEED_SIZE); int verticalSize = GetDeviceIntProperty(device, profile.PaperSource == ScanSource.Glass ? DeviceProperties.VERTICAL_BED_SIZE : DeviceProperties.VERTICAL_FEED_SIZE); int pagemaxwidth = horizontalSize * resolution / 1000; int pagemaxheight = verticalSize * resolution / 1000; int horizontalPos = 0; if (profile.PageAlign == ScanHorizontalAlign.Center) horizontalPos = (pagemaxwidth - pageWidth) / 2; else if (profile.PageAlign == ScanHorizontalAlign.Left) horizontalPos = (pagemaxwidth - pageWidth); pageWidth = pageWidth < pagemaxwidth ? pageWidth : pagemaxwidth; pageHeight = pageHeight < pagemaxheight ? pageHeight : pagemaxheight; if (profile.WiaOffsetWidth) { SetItemIntProperty(item, pageWidth + horizontalPos, ItemProperties.HORIZONTAL_EXTENT); SetItemIntProperty(item, horizontalPos, ItemProperties.HORIZONTAL_START); } else { SetItemIntProperty(item, horizontalPos, ItemProperties.HORIZONTAL_START); SetItemIntProperty(item, pageWidth, ItemProperties.HORIZONTAL_EXTENT); } SetItemIntProperty(item, pageHeight, ItemProperties.VERTICAL_EXTENT); if (!profile.BrightnessContrastAfterScan) { SetItemIntProperty(item, profile.Contrast, -1000, 1000, ItemProperties.CONTRAST); SetItemIntProperty(item, profile.Brightness, -1000, 1000, ItemProperties.BRIGHTNESS); } }