예제 #1
0
파일: FDesktop.cs 프로젝트: gas3/twain
        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));
        }
예제 #2
0
        public bool ShouldDoBackgroundOcr(ScanParams scanParams)
        {
            var ocrEnabled    = ocrManager.DefaultParams != null;
            var afterScanning = appConfigManager.Config.OcrState == OcrState.Enabled && appConfigManager.Config.OcrDefaultAfterScanning ||
                                appConfigManager.Config.OcrState == OcrState.UserConfig &&
                                (userConfigManager.Config.OcrAfterScanning ?? appConfigManager.Config.OcrDefaultAfterScanning);

            return(scanParams.DoOcr ?? (ocrEnabled && afterScanning));
        }
예제 #3
0
        protected override void onLoad()
        {
            var newBtn = Document.GetElementById <ButtonElement>("newBtn");

            newBtn.OnClick = (ev) =>
            {
                Navigation <New> .Go();
            };

            var dynamodb = new DynamoDB();

            var param = new ScanParams
            {
                TableName            = "stock",
                ProjectionExpression = "product, quantity"
            };

            dynamodb.scan(param, (err, data) =>
            {
                if (err != null)
                {
                    Toast.Error(err.stack.ToString()); // an error occurred
                }
                else
                {
                    foreach (var item in data.Items)
                    {
                        var row = new TableRowElement();

                        var productTD       = new TableDataCellElement();
                        productTD.InnerHTML = item.produto.S;

                        row.AppendChild(productTD);

                        var quantityTD       = new TableDataCellElement();
                        quantityTD.InnerHTML = item.quantidade.N;
                        row.AppendChild(quantityTD);

                        var editBtn       = new ButtonElement();
                        editBtn.ClassName = "btn btn-default";
                        editBtn.InnerHTML = "Edit";

                        var editTD = new TableDataCellElement();
                        editTD.AppendChild(editBtn);
                        editBtn.OnClick = (ev) =>
                        {
                            Navigation <Edit> .Go(item.produto.S, int.Parse(item.quantidade.N));
                        };

                        row.AppendChild(editTD);

                        var tbody = Document.GetElementById <TableSectionElement>("table-body");
                        tbody.AppendChild(row);
                    }
                }
            });
        }
예제 #4
0
 public string SaveForBackgroundOcr(Bitmap bitmap, ScanParams scanParams)
 {
     if (ShouldDoBackgroundOcr(scanParams))
     {
         string tempPath = Path.Combine(Paths.Temp, Path.GetRandomFileName());
         bitmap.Save(tempPath);
         return(tempPath);
     }
     return(null);
 }
예제 #5
0
        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);
        }
예제 #6
0
        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);
        }
예제 #7
0
 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));
     }
 }
예제 #8
0
 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;
             }
         }
     }
 }
예제 #9
0
 public void RunBackgroundOcr(ScannedImage image, ScanParams scanParams, string tempPath)
 {
     if (ShouldDoBackgroundOcr(scanParams))
     {
         using (var snapshot = image.Preserve())
         {
             if (scanParams.DoOcr == true)
             {
                 ocrRequestQueue.QueueForeground(null, snapshot, tempPath, scanParams.OcrParams, scanParams.OcrCancelToken).AssertNoAwait();
             }
             else
             {
                 ocrRequestQueue.QueueBackground(snapshot, tempPath, scanParams.OcrParams);
             }
         }
     }
 }
예제 #10
0
        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);
            }
        }
예제 #11
0
 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();
 }
            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)
                {
                }
            }
예제 #13
0
        private void ConfigureDS(DataSource ds, ScanProfile scanProfile, ScanParams scanParams)
        {
            if (scanProfile.UseNativeUI)
            {
                return;
            }

            // Transfer Mode
            if (scanProfile.TwainImpl == TwainImpl.MemXfer)
            {
                ds.Capabilities.ICapXferMech.SetValue(XferMech.Memory);
            }

            // 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);
            }
        }
예제 #14
0
 public List <RecoveryIndexImage> TwainScan(int recoveryFileNumber, ScanDevice scanDevice, ScanProfile scanProfile, ScanParams scanParams)
 {
     RecoveryImage.RecoveryFileNumber = recoveryFileNumber;
     return(twainWrapper.Scan(ParentForm, true, scanDevice, scanProfile, scanParams).Select(x => x.RecoveryIndexImage).ToList());
 }
예제 #15
0
        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);
            }
        }
예제 #16
0
 public void scan(ScanParams param, Action <DynamoError, ScanData> callback)
 {
     return;
 }
예제 #17
0
        private void InternalScan(TwainImpl twainImpl, IWin32Window dialogParent, ScanDevice scanDevice, ScanProfile scanProfile, ScanParams scanParams,
                                  CancellationToken cancelToken, ScannedImageSource.Concrete source, Action <ScannedImage, ScanParams, string> runBackgroundOcr)
        {
            if (dialogParent == null)
            {
                dialogParent = new BackgroundForm();
            }
            if (twainImpl == TwainImpl.Legacy)
            {
                Legacy.TwainApi.Scan(scanProfile, scanDevice, dialogParent, formFactory, source);
                return;
            }

            PlatformInfo.Current.PreferNewDSM = twainImpl != TwainImpl.OldDsm;
            var        session    = new TwainSession(TwainAppId);
            var        twainForm  = Invoker.Current.InvokeGet(() => scanParams.NoUI ? null : formFactory.Create <FTwainGui>());
            Exception  error      = null;
            bool       cancel     = false;
            DataSource ds         = null;
            var        waitHandle = new AutoResetEvent(false);

            int pageNumber = 0;

            session.TransferReady += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - TransferReady");
                if (cancel)
                {
                    eventArgs.CancelAll = true;
                }
            };
            session.DataTransferred += (sender, eventArgs) =>
            {
                try
                {
                    Debug.WriteLine("NAPS2.TW - DataTransferred");
                    pageNumber++;
                    using (var output = twainImpl == TwainImpl.MemXfer
                                        ? GetBitmapFromMemXFer(eventArgs.MemoryData, eventArgs.ImageInfo)
                                        : 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);
                            if (scanParams.DetectPatchCodes)
                            {
                                foreach (var patchCodeInfo in eventArgs.GetExtImageInfo(ExtendedImageInfo.PatchCode))
                                {
                                    if (patchCodeInfo.ReturnCode == ReturnCode.Success)
                                    {
                                        image.PatchCode = GetPatchCode(patchCodeInfo);
                                    }
                                }
                            }
                            scannedImageHelper.PostProcessStep2(image, result, scanProfile, scanParams, pageNumber);
                            string tempPath = scannedImageHelper.SaveForBackgroundOcr(result, scanParams);
                            runBackgroundOcr(image, scanParams, tempPath);
                            source.Put(image);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("NAPS2.TW - DataTransferred - Error");
                    error  = ex;
                    cancel = true;
                    StopTwain();
                }
            };
            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;
                StopTwain();
            };
            session.SourceDisabled += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - SourceDisabled");
                StopTwain();
            };

            void StopTwain()
            {
                waitHandle.Set();
                if (!scanParams.NoUI)
                {
                    Invoker.Current.Invoke(() => twainForm.Close());
                }
            }

            void InitTwain()
            {
                try
                {
                    var        windowHandle = (Invoker.Current as Form)?.Handle;
                    ReturnCode rc           = windowHandle != null?session.Open(new WindowsFormsMessageLoopHook(windowHandle.Value)) : session.Open();

                    if (rc != ReturnCode.Success)
                    {
                        Debug.WriteLine("NAPS2.TW - Could not open session - {0}", rc);
                        StopTwain();
                        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);
                        StopTwain();
                        return;
                    }
                    ConfigureDS(ds, scanProfile, scanParams);
                    var ui = scanProfile.UseNativeUI ? SourceEnableMode.ShowUI : SourceEnableMode.NoUI;
                    Debug.WriteLine("NAPS2.TW - Enabling DS");
                    rc = scanParams.NoUI ? ds.Enable(ui, true, windowHandle ?? IntPtr.Zero) : ds.Enable(ui, true, twainForm.Handle);
                    Debug.WriteLine("NAPS2.TW - Enable finished");
                    if (rc != ReturnCode.Success)
                    {
                        Debug.WriteLine("NAPS2.TW - Enable failed - {0}, rc");
                        StopTwain();
                    }
                    else
                    {
                        cancelToken.Register(() =>
                        {
                            Debug.WriteLine("NAPS2.TW - User Cancel");
                            cancel = true;
                            session.ForceStepDown(5);
                        });
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("NAPS2.TW - Error");
                    error = ex;
                    StopTwain();
                }
            }

            if (!scanParams.NoUI)
            {
                twainForm.Shown  += (sender, eventArgs) => { InitTwain(); };
                twainForm.Closed += (sender, args) => waitHandle.Set();
            }

            if (scanParams.NoUI)
            {
                Debug.WriteLine("NAPS2.TW - Init with no form");
                Invoker.Current.Invoke(InitTwain);
            }
            else if (!scanParams.Modal)
            {
                Debug.WriteLine("NAPS2.TW - Init with non-modal form");
                Invoker.Current.Invoke(() => twainForm.Show(dialogParent));
            }
            else
            {
                Debug.WriteLine("NAPS2.TW - Init with modal form");
                Invoker.Current.Invoke(() => twainForm.ShowDialog(dialogParent));
            }
            waitHandle.WaitOne();
            Debug.WriteLine("NAPS2.TW - Operation complete");

            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);
            }
        }
예제 #18
0
        private void StartBarcode()
        {
            if (m_ScanBuffer != null) return;
            VmMdVendorFactory.Instance.Log("Entered StartBarcode");

            Mot.PdaSdk.ScanAPI.Scanner.Instance.Enable();
            m_ScanBuffer = new ScanBuffer();
            Triggers.Instance.TriggerEvent += new Mot.PdaSdk.TriggersApi.Triggers.TriggerEventHandler(Instance_TriggerEvent);

            Triggers.Instance.EnableEvents();

            ScanParams scanParams = new ScanParams();
            Mot.PdaSdk.ScanAPI.Scanner.Instance.GetScanParams(scanParams);
            scanParams.ControlScanLed = true;
            scanParams.DecodeLedTime = 2000;
            scanParams.FatalLedTime = 2000;
            scanParams.NonfatalLedTime = 2000;
            Mot.PdaSdk.ScanAPI.Scanner.Instance.SetScanParams(scanParams);

            ArrayList decoders = new ArrayList();
            decoders.Add(LabelType.CODE39);
            decoders.Add(LabelType.CODE128);
            if( _allowCode93 ) decoders.Add(LabelType.CODE93);
            Mot.PdaSdk.ScanAPI.Scanner.Instance.SetEnabledDecoders(decoders);

            DecodeMode p = new DecodeMode();
            Mot.PdaSdk.ScanAPI.Scanner.Instance.GetInternalImagerParams(p);
            p.DecodingMode = DecodeModeType.ADVANCED_LINEAR;
            Mot.PdaSdk.ScanAPI.Scanner.Instance.SetInternalImagerParams(p);

            DecodeLimitTime limitTime = new DecodeLimitTime();
            Mot.PdaSdk.ScanAPI.Scanner.Instance.GetInternalImagerParams(limitTime);
            limitTime.DecodeLimit = 400;
            limitTime.SearchLimit = 400;
            Mot.PdaSdk.ScanAPI.Scanner.Instance.SetInternalImagerParams(limitTime);
        }
예제 #19
0
 public JsonRpcResponse <string> Scan(ScanParams parameters, string requestId = "VideoLibrary.Scan")
 {
     return(_rpcConnector.MakeRequest <string>(KodiMethods.Scan, parameters, requestId));
 }
예제 #20
0
 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.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);
     }
 }
예제 #21
0
        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;
        }
예제 #22
0
        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));
            }

            PlatformInfo.Current.PreferNewDSM = scanProfile.TwainImpl != TwainImpl.OldDsm;
            var        session   = new TwainSession(TwainAppId);
            var        twainForm = formFactory.Create <FTwainGui>();
            var        images    = new List <ScannedImage>();
            Exception  error     = null;
            bool       cancel    = false;
            DataSource ds        = null;

            int pageNumber = 0;

            session.TransferReady += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - TransferReady");
                if (cancel)
                {
                    eventArgs.CancelAll = true;
                }
            };
            session.DataTransferred += (sender, eventArgs) =>
            {
                try
                {
                    Debug.WriteLine("NAPS2.TW - DataTransferred");
                    pageNumber++;
                    using (var output = scanProfile.TwainImpl == TwainImpl.MemXfer
                                        ? GetBitmapFromMemXFer(eventArgs.MemoryData, eventArgs.ImageInfo)
                                        : 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);
                            image.SetThumbnail(thumbnailRenderer.RenderThumbnail(result));
                            if (scanParams.DetectPatchCodes)
                            {
                                foreach (var patchCodeInfo in eventArgs.GetExtImageInfo(ExtendedImageInfo.PatchCode))
                                {
                                    if (patchCodeInfo.ReturnCode == ReturnCode.Success)
                                    {
                                        image.PatchCode = GetPatchCode(patchCodeInfo);
                                    }
                                }
                            }
                            scannedImageHelper.PostProcessStep2(image, result, scanProfile, scanParams, pageNumber);
                            images.Add(image);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("NAPS2.TW - DataTransferred - Error");
                    error  = ex;
                    cancel = true;
                    twainForm.Close();
                }
            };
            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);
        }
예제 #23
0
        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)
            {
                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;
                    }
                }
            }
        }
예제 #24
0
 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();
 }
예제 #25
0
 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;
         }
     }
 }
예제 #26
0
        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)
            {
                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;
                    }
                }
            }
            else if (scanParams.DetectBarcodes)
            {
                IMultipleBarcodeReader multiReader = new BarcodeReader();
                multiReader.Options.TryHarder = true;
                // profile.AutoSaveSettings.Separator == ImportExport.SaveSeparator.Barcode
                if (profile.AutoSaveSettings != null)
                {
                    if (profile.AutoSaveSettings.BarcodeType != null && profile.AutoSaveSettings.BarcodeType != "")
                    {
                        switch (profile.AutoSaveSettings.BarcodeType)
                        {
                        case "2of5 interleaved":
                            multiReader.Options.PossibleFormats = new List <BarcodeFormat>();
                            multiReader.Options.PossibleFormats.Add(BarcodeFormat.ITF);
                            break;

                        case "Code 39":
                            multiReader.Options.PossibleFormats = new List <BarcodeFormat>();
                            multiReader.Options.PossibleFormats.Add(BarcodeFormat.CODE_39);
                            break;

                        case "Code 93":
                            multiReader.Options.PossibleFormats = new List <BarcodeFormat>();
                            multiReader.Options.PossibleFormats.Add(BarcodeFormat.CODE_93);
                            break;

                        case "Code 128":
                            multiReader.Options.PossibleFormats = new List <BarcodeFormat>();
                            multiReader.Options.PossibleFormats.Add(BarcodeFormat.CODE_128);
                            break;

                        case "EAN 8":
                            multiReader.Options.PossibleFormats = new List <BarcodeFormat>();
                            multiReader.Options.PossibleFormats.Add(BarcodeFormat.EAN_8);
                            break;

                        case "EAN13":
                            multiReader.Options.PossibleFormats = new List <BarcodeFormat>();
                            multiReader.Options.PossibleFormats.Add(BarcodeFormat.EAN_13);
                            break;
                        }
                    }
                }

                var barcodeResult = multiReader.DecodeMultiple(bitmap);
                if (barcodeResult != null)
                {
                    foreach (var barcode in barcodeResult)
                    {
                        image.Barcode = barcode.Text;
                        System.Diagnostics.Debug.WriteLine(barcode.BarcodeFormat + " = " + barcode.Text);
                    }
                }
            }
        }