Example #1
0
 private void btnOK_Click(object sender, EventArgs e)
 {
     if (!CropTransform.IsNull)
     {
         if (TransformMultiple)
         {
             // With multiple images, we need to have the transform scaled in case they're different sizes
             using (var referenceBitmap = scannedImageRenderer.Render(Image))
             {
                 foreach (var img in ImagesToTransform)
                 {
                     img.AddTransform(ScaleCropTransform(img, referenceBitmap));
                     img.SetThumbnail(thumbnailRenderer.RenderThumbnail(img));
                 }
             }
         }
         else
         {
             Image.AddTransform(CropTransform);
             Image.SetThumbnail(thumbnailRenderer.RenderThumbnail(Image));
         }
         changeTracker.HasUnsavedChanges = true;
     }
     Close();
 }
Example #2
0
        private async Task <ScannedImage> ExportRawPdfPage(PdfPage page, ImportParams importParams)
        {
            string pdfPath  = Path.Combine(Paths.Temp, Path.GetRandomFileName());
            var    document = new PdfDocument();

            document.Pages.Add(page);
            document.Save(pdfPath);

            var image = ScannedImage.FromSinglePagePdf(pdfPath, false);

            if (!importParams.NoThumbnails || importParams.DetectPatchCodes)
            {
                using (var bitmap = await scannedImageRenderer.Render(image))
                {
                    if (!importParams.NoThumbnails)
                    {
                        image.SetThumbnail(thumbnailRenderer.RenderThumbnail(bitmap));
                    }
                    if (importParams.DetectPatchCodes)
                    {
                        image.PatchCode = PatchCodeDetector.Detect(bitmap);
                    }
                }
            }
            return(image);
        }
Example #3
0
 private ScannedImage ExportJpegImage(PdfPage page, byte[] imageBytes)
 {
     // Fortunately JPEG has native support in PDF and exporting an image is just writing the stream to a file.
     using (var memoryStream = new MemoryStream(imageBytes))
     {
         using (var bitmap = new Bitmap(memoryStream))
         {
             bitmap.SetResolution(bitmap.Width / (float)page.Width.Inch, bitmap.Height / (float)page.Height.Inch);
             var image = new ScannedImage(bitmap, ScanBitDepth.C24Bit, false, -1);
             image.SetThumbnail(thumbnailRenderer.RenderThumbnail(bitmap));
             return(image);
         }
     }
 }
Example #4
0
            private bool DoRecover(Action <ScannedImage> imageCallback)
            {
                Status.MaxProgress = recoveryIndexManager.Index.Images.Count;
                InvokeStatusChanged();

                foreach (RecoveryIndexImage indexImage in recoveryIndexManager.Index.Images)
                {
                    if (cancel)
                    {
                        return(false);
                    }

                    string       imagePath = Path.Combine(folderToRecoverFrom.FullName, indexImage.FileName);
                    ScannedImage scannedImage;
                    using (var bitmap = new Bitmap(imagePath))
                    {
                        scannedImage = new ScannedImage(bitmap, indexImage.BitDepth, indexImage.HighQuality, -1);
                    }
                    foreach (var transform in indexImage.TransformList)
                    {
                        scannedImage.AddTransform(transform);
                    }
                    scannedImage.SetThumbnail(thumbnailRenderer.RenderThumbnail(scannedImage));
                    imageCallback(scannedImage);

                    Status.CurrentProgress++;
                    InvokeStatusChanged();
                }
                return(true);
            }
Example #5
0
        private ScannedImage ExportRawPdfPage(PdfPage page)
        {
            string pdfPath  = Path.Combine(Paths.Temp, Path.GetRandomFileName());
            var    document = new PdfDocument();

            document.Pages.Add(page);
            document.Save(pdfPath);

            var image = ScannedImage.FromSinglePagePdf(pdfPath, false);

            using (var bitmap = scannedImageRenderer.Render(image))
            {
                image.SetThumbnail(thumbnailRenderer.RenderThumbnail(bitmap));
            }
            return(image);
        }
Example #6
0
        public IEnumerable <ScannedImage> Import(string filePath, Func <int, int, bool> progressCallback)
        {
            if (!progressCallback(0, 1))
            {
                yield break;
            }
            Bitmap toImport;

            try
            {
                toImport = new Bitmap(filePath);
            }
            catch (Exception e)
            {
                Log.ErrorException("Error importing image: " + filePath, e);
                // Handle and notify the user outside the method so that errors importing multiple files can be aggregated
                throw;
            }
            using (toImport)
            {
                int frameCount = toImport.GetFrameCount(FrameDimension.Page);
                for (int i = 0; i < frameCount; ++i)
                {
                    if (!progressCallback(i, frameCount))
                    {
                        yield break;
                    }
                    toImport.SelectActiveFrame(FrameDimension.Page, i);
                    var image = new ScannedImage(toImport, ScanBitDepth.C24Bit, IsLossless(toImport.RawFormat), -1);
                    image.SetThumbnail(thumbnailRenderer.RenderThumbnail(toImport));
                    yield return(image);
                }
                progressCallback(frameCount, frameCount);
            }
        }
Example #7
0
 private void btnOK_Click(object sender, EventArgs e)
 {
     if (!RotationTransform.IsNull)
     {
         foreach (var img in ImagesToTransform)
         {
             img.AddTransform(RotationTransform);
             img.SetThumbnail(thumbnailRenderer.RenderThumbnail(img));
         }
         changeTracker.HasUnsavedChanges = true;
     }
     Close();
 }
Example #8
0
 private void btnOK_Click(object sender, EventArgs e)
 {
     if (!BlackWhiteTransform.IsNull)
     {
         Parallel.ForEach(ImagesToTransform, img =>
         {
             img.AddTransform(BlackWhiteTransform);
             img.SetThumbnail(thumbnailRenderer.RenderThumbnail(img));
         });
         changeTracker.HasUnsavedChanges = true;
     }
     Close();
 }
Example #9
0
 private ScannedImage TransferImage(WiaBackgroundEventLoop eventLoop, int pageNumber, out bool cancel)
 {
     try
     {
         // TODO: Use the NoUI flag uniformly
         var transfer = ScanParams.NoUI ? new ConsoleWiaTransfer() : wiaTransfer;
         using (var stream = transfer.Transfer(pageNumber, eventLoop, WiaApi.Formats.BMP))
         {
             if (stream == null)
             {
                 cancel = true;
                 return(null);
             }
             cancel = false;
             using (Image output = Image.FromStream(stream))
             {
                 using (var result = ScannedImageHelper.PostProcessStep1(output, ScanProfile))
                 {
                     if (blankDetector.ExcludePage(result, ScanProfile))
                     {
                         return(null);
                     }
                     ScanBitDepth bitDepth = ScanProfile.UseNativeUI ? ScanBitDepth.C24Bit : ScanProfile.BitDepth;
                     var          image    = new ScannedImage(result, bitDepth, ScanProfile.MaxQuality, ScanProfile.Quality);
                     image.SetThumbnail(thumbnailRenderer.RenderThumbnail(result));
                     ScannedImageHelper.PostProcessStep2(image, ScanProfile, pageNumber);
                     return(image);
                 }
             }
         }
     }
     catch (NoPagesException)
     {
         if (ScanProfile.PaperSource != ScanSource.Glass && pageNumber == 1)
         {
             // No pages were in the feeder, so show the user an error
             throw new NoPagesException();
         }
         // At least one page was scanned but now the feeder is empty, so exit normally
         cancel = true;
         return(null);
     }
     catch (ScanDriverException)
     {
         throw;
     }
     catch (Exception e)
     {
         throw new ScanDriverUnknownException(e);
     }
 }
Example #10
0
        public bool Start(DirectImageTransfer data, bool copy, Action <ScannedImage> imageCallback)
        {
            ProgressTitle = copy ? MiscResources.CopyProgress : MiscResources.ImportProgress;
            Status        = new OperationStatus
            {
                StatusText  = copy ? MiscResources.Copying : MiscResources.Importing,
                MaxProgress = data.ImageRecovery.Length
            };
            cancel = false;

            thread = threadFactory.StartThread(() =>
            {
                Exception error = null;
                foreach (var ir in data.ImageRecovery)
                {
                    try
                    {
                        ScannedImage img;
                        using (var bitmap = new Bitmap(Path.Combine(data.RecoveryFolder, ir.FileName)))
                        {
                            img = new ScannedImage(bitmap, ir.BitDepth, ir.HighQuality, -1);
                        }
                        foreach (var transform in ir.TransformList)
                        {
                            img.AddTransform(transform);
                        }
                        img.SetThumbnail(thumbnailRenderer.RenderThumbnail(img));
                        imageCallback(img);

                        Status.CurrentProgress++;
                        InvokeStatusChanged();
                        if (cancel)
                        {
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        error = ex;
                    }
                }
                if (error != null)
                {
                    Log.ErrorException(string.Format(MiscResources.ImportErrorCouldNot, data.RecoveryFolder), error);
                }
                Status.Success = true;
                InvokeFinished();
            });
            return(true);
        }
Example #11
0
        public bool Start(DirectImageTransfer data, bool copy, Action <ScannedImage> imageCallback)
        {
            ProgressTitle = copy ? MiscResources.CopyProgress : MiscResources.ImportProgress;
            Status        = new OperationStatus
            {
                StatusText  = copy ? MiscResources.Copying : MiscResources.Importing,
                MaxProgress = data.ImageRecovery.Length
            };

            RunAsync(async() =>
            {
                Exception error = null;
                foreach (var ir in data.ImageRecovery)
                {
                    try
                    {
                        ScannedImage img;
                        using (var bitmap = new Bitmap(Path.Combine(data.RecoveryFolder, ir.FileName)))
                        {
                            img = new ScannedImage(bitmap, ir.BitDepth, ir.HighQuality, -1);
                        }
                        foreach (var transform in ir.TransformList)
                        {
                            img.AddTransform(transform);
                        }
                        // TODO: Don't bother, here, in recovery, etc.
                        img.SetThumbnail(await thumbnailRenderer.RenderThumbnail(img));
                        imageCallback(img);

                        Status.CurrentProgress++;
                        InvokeStatusChanged();
                        if (CancelToken.IsCancellationRequested)
                        {
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        error = ex;
                    }
                }
                if (error != null)
                {
                    Log.ErrorException(string.Format(MiscResources.ImportErrorCouldNot, data.RecoveryFolder), error);
                }
                return(true);
            });
            return(true);
        }
Example #12
0
            private async Task <bool> DoRecover(Action <ScannedImage> imageCallback)
            {
                Status.MaxProgress = recoveryIndexManager.Index.Images.Count;
                InvokeStatusChanged();

                foreach (RecoveryIndexImage indexImage in recoveryIndexManager.Index.Images)
                {
                    if (CancelToken.IsCancellationRequested)
                    {
                        return(false);
                    }

                    string       imagePath = Path.Combine(folderToRecoverFrom.FullName, indexImage.FileName);
                    ScannedImage scannedImage;
                    if (".pdf".Equals(Path.GetExtension(imagePath), StringComparison.InvariantCultureIgnoreCase))
                    {
                        scannedImage = ScannedImage.FromSinglePagePdf(imagePath, true);
                    }
                    else
                    {
                        using (var bitmap = new Bitmap(imagePath))
                        {
                            scannedImage = new ScannedImage(bitmap, indexImage.BitDepth, indexImage.HighQuality, -1);
                        }
                    }
                    foreach (var transform in indexImage.TransformList)
                    {
                        scannedImage.AddTransform(transform);
                    }
                    scannedImage.SetThumbnail(await thumbnailRenderer.RenderThumbnail(scannedImage));
                    imageCallback(scannedImage);

                    Status.CurrentProgress++;
                    InvokeStatusChanged();
                }
                return(true);
            }
Example #13
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);
        }
Example #14
0
        public ScannedImageSource Import(string filePath, ImportParams importParams, ProgressHandler progressCallback, CancellationToken cancelToken)
        {
            var source = new ScannedImageSource.Concrete();

            Task.Factory.StartNew(() =>
            {
                try
                {
                    if (cancelToken.IsCancellationRequested)
                    {
                        source.Done();
                        return;
                    }

                    Bitmap toImport;
                    try
                    {
                        toImport = new Bitmap(filePath);
                    }
                    catch (Exception e)
                    {
                        Log.ErrorException("Error importing image: " + filePath, e);
                        // Handle and notify the user outside the method so that errors importing multiple files can be aggregated
                        throw;
                    }

                    using (toImport)
                    {
                        int frameCount = toImport.GetFrameCount(FrameDimension.Page);
                        int i          = 0;
                        foreach (var frameIndex in importParams.Slice.Indices(frameCount))
                        {
                            progressCallback(i++, frameCount);
                            if (cancelToken.IsCancellationRequested)
                            {
                                source.Done();
                                return;
                            }

                            toImport.SelectActiveFrame(FrameDimension.Page, frameIndex);
                            var image = new ScannedImage(toImport, ScanBitDepth.C24Bit, IsLossless(toImport.RawFormat), -1);
                            if (!importParams.NoThumbnails)
                            {
                                image.SetThumbnail(thumbnailRenderer.RenderThumbnail(toImport));
                            }
                            if (importParams.DetectPatchCodes)
                            {
                                image.PatchCode = PatchCodeDetector.Detect(toImport);
                            }

                            source.Put(image);
                        }

                        progressCallback(frameCount, frameCount);
                    }
                    source.Done();
                }
                catch (Exception e)
                {
                    source.Error(e);
                }
            }, TaskCreationOptions.LongRunning);
            return(source);
        }