/// <summary> /// Constructs a receiver for scanned images. /// This keeps images from the same source together, even if multiple sources are providing images at the same time. /// </summary> /// <returns></returns> public Action <ScannedImage> ReceiveScannedImage() { ScannedImage last = null; return(scannedImage => { SafeInvoke(() => { lock (imageList) { // Default to the end of the list int index = imageList.Images.Count; // Use the index after the last image from the same source (if it exists) if (last != null) { int lastIndex = imageList.Images.IndexOf(last); if (lastIndex != -1) { index = lastIndex + 1; } } imageList.Images.Insert(index, scannedImage); scannedImage.MovedTo(index); last = scannedImage; } }); }); }
private void DoSaveImage(ScannedImage image, string path, ImageFormat format) { PathHelper.EnsureParentDirExists(path); if (Equals(format, ImageFormat.Tiff)) { tiffHelper.SaveMultipage(new List <ScannedImage> { image }, path, imageSettingsContainer.ImageSettings.TiffCompression, i => true); } else if (Equals(format, ImageFormat.Jpeg)) { var quality = Math.Max(Math.Min(imageSettingsContainer.ImageSettings.JpegQuality, 100), 0); var encoder = ImageCodecInfo.GetImageEncoders().First(x => x.FormatID == ImageFormat.Jpeg.Guid); var encoderParams = new EncoderParameters(1); encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, quality); using (Bitmap bitmap = scannedImageRenderer.Render(image)) { bitmap.Save(path, encoder, encoderParams); } } else { using (Bitmap bitmap = scannedImageRenderer.Render(image)) { bitmap.Save(path, format); } } }
private void bStart_Click(object sender, EventArgs e) { if (oTeacher.Images.Next()) { ScannedImage oImage = oTeacher.Images[oTeacher.Images.Index]; oImage.FileType = "JPEG"; img.FileName = oImage.FilePath; if (oOrder.Find(oImage.OrderID)) { frmOrder ofrmOrder = new frmOrder(oOrder); ofrmOrder._OrderProcess = (int)OrderProcess.Scanning; ofrmOrder.ShowDialog(); if (ofrmOrder.IsSaved) { oImage.OrderID = Convert.ToInt32(ofrmOrder.oOrder.ID); oImage.Message = "Saved and Corrected"; oImage.Status = ScannedOrderStatus.ProcessedAndCorrected; oImage.UpdateStatus(); } ofrmOrder.Dispose(); } this.bStart_Click(null, null); } else { MessageBox.Show("No more Images"); } }
protected virtual void ProcessImageData(ScannedImage image) { if (image.IsScannable) { this.m_id = image.TemplateName; } }
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); }
public void ReceiveScannedImage(ScannedImage scannedImage) { scanList.Last().Add(scannedImage); pagesScanned++; totalPagesScanned++; OutputVerbose(ConsoleResources.ScannedPage, totalPagesScanned); }
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); } }
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); }
private PdfPage CopyPdfPageToDoc(PdfDocument destDoc, ScannedImage image) { // Pull the PDF content directly to maintain objects, dpi, etc. PdfDocument sourceDoc = PdfReader.Open(image.RecoveryFilePath, PdfDocumentOpenMode.Import); PdfPage sourcePage = sourceDoc.Pages.Cast<PdfPage>().Single(); PdfPage destPage = destDoc.AddPage(sourcePage); destPage.CustomValues["/NAPS2ImportedPage"] = new PdfCustomValue(new byte[] { 0xFF }); return destPage; }
public void TwainImageReceived(RecoveryIndexImage image, byte[] thumbnail, string tempImageFilePath) { var scannedImage = new ScannedImage(image); if (thumbnail != null) { scannedImage.SetThumbnail(new Bitmap(new MemoryStream(thumbnail))); } ImageCallback?.Invoke(scannedImage, tempImageFilePath); }
private async Task <(ScannedImage, bool)> Transfer(Lazy <KeyValueScanOptions> options, int pageNumber) { return(await Task.Factory.StartNew(() => { Stream stream; if (ScanParams.NoUi) { stream = saneWrapper.ScanOne(ScanDevice.Id, options.Value, null, CancelToken); } else { var form = formFactory.Create <FScanProgress>(); var unifiedCancelToken = CancellationTokenSource.CreateLinkedTokenSource(form.CancelToken, CancelToken).Token; form.Transfer = () => saneWrapper.ScanOne(ScanDevice.Id, options.Value, form.OnProgress, unifiedCancelToken); form.PageNumber = pageNumber; ((FormBase)Application.OpenForms[0]).SafeInvoke(() => form.ShowDialog()); if (form.Exception != null) { form.Exception.PreserveStackTrace(); throw form.Exception; } if (form.DialogResult == DialogResult.Cancel) { return (null, true); } stream = form.ImageStream; } if (stream == null) { return (null, true); } using (stream) using (var output = Image.FromStream(stream)) using (var result = scannedImageHelper.PostProcessStep1(output, ScanProfile, false)) { if (blankDetector.ExcludePage(result, ScanProfile)) { return (null, false); } // By converting to 1bpp here we avoid the Win32 call in the BitmapHelper conversion // This converter also has the side effect of working even if the scanner doesn't support Lineart using (var encoded = ScanProfile.BitDepth == ScanBitDepth.BlackWhite ? UnsafeImageOps.ConvertTo1Bpp(result, -ScanProfile.Brightness) : result) { var image = new ScannedImage(encoded, ScanProfile.BitDepth, ScanProfile.MaxQuality, ScanProfile.Quality); scannedImageHelper.PostProcessStep2(image, result, ScanProfile, ScanParams, 1, false); var tempPath = scannedImageHelper.SaveForBackgroundOcr(result, ScanParams); scannedImageHelper.RunBackgroundOcr(image, ScanParams, tempPath); return (image, false); } } }, TaskCreationOptions.LongRunning)); }
/// <summary> /// Process image data /// </summary> /// <param name="image"></param> protected override void ProcessImageData(ScannedImage image) { base.ProcessImageData(image); if (image.IsScannable) { m_topLeft = image.FormArea[0]; m_topRight = image.FormArea[1]; m_bottomRight = image.FormArea[2]; m_bottomLeft = image.FormArea[3]; } }
public override int GetHashCode() { unchecked { var hashCode = (ScannedImage != null ? ScannedImage.GetHashCode() : 0); hashCode = (hashCode * 397) ^ TransformState; hashCode = (hashCode * 397) ^ (Engine != null ? Engine.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (OcrParams != null ? OcrParams.GetHashCode() : 0); return(hashCode); } }
private ScannedImage ExportG4(PdfPage page, PdfDictionary imageObject, byte[] imageBytes, ImportParams importParams) { int width = imageObject.Elements.GetInteger(PdfImage.Keys.Width); int height = imageObject.Elements.GetInteger(PdfImage.Keys.Height); int bitsPerComponent = imageObject.Elements.GetInteger(PdfImage.Keys.BitsPerComponent); // We don't have easy access to a standalone CCITT G4 decoder, so we'll make use of the .NET TIFF decoder // by constructing a valid TIFF file "manually" and directly injecting the bytestream var stream = new MemoryStream(); Write(stream, TiffBeforeDataLen); // The bytestream is 2-padded, so we may need to append an extra zero byte if (imageBytes.Length % 2 == 1) { Write(stream, imageBytes.Length + 0x11); } else { Write(stream, imageBytes.Length + 0x10); } Write(stream, TiffBeforeData); Write(stream, imageBytes); if (imageBytes.Length % 2 == 1) { Write(stream, new byte[] { 0x00 }); } Write(stream, TiffBeforeWidth); Write(stream, width); Write(stream, TiffBeforeHeight); Write(stream, height); Write(stream, TiffBeforeBits); Write(stream, bitsPerComponent); Write(stream, TiffBeforeRealLen); Write(stream, imageBytes.Length); Write(stream, TiffTrailer); stream.Seek(0, SeekOrigin.Begin); using (Bitmap bitmap = (Bitmap)Image.FromStream(stream)) { bitmap.SafeSetResolution(bitmap.Width / (float)page.Width.Inch, bitmap.Height / (float)page.Height.Inch); var image = new ScannedImage(bitmap, ScanBitDepth.BlackWhite, true, -1); if (!importParams.NoThumbnails) { image.SetThumbnail(thumbnailRenderer.RenderThumbnail(bitmap)); } if (importParams.DetectPatchCodes) { image.PatchCode = PatchCodeDetector.Detect(bitmap); } return(image); } }
public override void Put(ScannedImage image) { MemoryStream stream = null; var thumb = image.GetThumbnail(); if (thumb != null) { stream = new MemoryStream(); thumb.Save(stream, ImageFormat.Png); } callback.TwainImageReceived(image.RecoveryIndexImage, stream?.ToArray(), imagePathDict.Get(image)); }
public frmOrderZonalAdquire() { InitializeComponent(); tw = new CTwain(); tw.Init(this.Handle); oCustomer = new ScannedCustomer(Global.CurrrentCompany); oTeacher = new ScannedTeacher(Global.CurrrentCompany); oImage = new ScannedImage(); } //Constructor
private void AddToListView(ScannedImage item) { var listViewItem = listView.Items.Add(item.DateScanned.ToString("G")); listViewItem.SubItems.Add(item.Name); listViewItem.SubItems.Add(item.Pages.ToString()); listViewItem.SubItems.Add(item.FileType); listViewItem.SubItems.Add(item.Routing.DocumentaryName); listViewItem.SubItems.Add(item.Routing.CertificateName); listViewItem.SubItems.Add(item.Routing.FolderPath); listViewItem.Tag = item; }
private ScannedImage MakeImage() { var bitmap = new Bitmap(600, 800); using (Graphics g = Graphics.FromImage(bitmap)) { g.FillRectangle(Brushes.LightGray, 0, 0, bitmap.Width, bitmap.Height); g.DrawString((_number++).ToString("G"), new Font("Times New Roman", 80), Brushes.Black, 0, 350); } var image = new ScannedImage(bitmap, ScanBitDepth.C24Bit, ScanProfile.MaxQuality, ScanProfile.Quality); return(image); }
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); } }
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); } } }
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); }
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); }
private CropTransform ScaleCropTransform(ScannedImage img, Bitmap referenceBitmap) { using (var bitmap = scannedImageRenderer.Render(img)) { double xScale = bitmap.Width / (double)referenceBitmap.Width, yScale = bitmap.Height / (double)referenceBitmap.Height; return(new CropTransform { Left = (int)Math.Round(CropTransform.Left * xScale), Right = (int)Math.Round(CropTransform.Right * xScale), Top = (int)Math.Round(CropTransform.Top * yScale), Bottom = (int)Math.Round(CropTransform.Bottom * yScale) }); } }
/// <summary> /// Create an OmrTemplate instance from the scanned image /// </summary> public static OmrTemplate FromFile(String fileName) { OmrTemplate retVal = new OmrTemplate(); retVal.SourcePath = fileName; // Input image ScannedImage inputImage = new ScannedImage(fileName); // Analyze the image inputImage.Analyze(); retVal.ImageSource = inputImage.Image; retVal.ProcessImageData(inputImage); return(retVal); }
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); }
/// <summary> /// Background process to do work /// </summary> private void bwImageProcess_DoWork(object sender, DoWorkEventArgs e) { if (this.m_processQueue.Count > 0) { Image image = null; lock (this.m_syncObject) image = Image.FromFile(m_processQueue.Dequeue()); image.RotateFlip(RotateFlipType.Rotate270FlipNone); Engine engineProcessor = new Engine(); var scannedImage = new ScannedImage(image); var output = engineProcessor.ApplyTemplate(this.m_currentTemplate, scannedImage); e.Result = output; image.Dispose(); scannedImage.Dispose(); } }
private async Task <(ScannedImage, bool)> TransferImage(WiaBackgroundEventLoop eventLoop, int pageNumber) { return(await Task.Factory.StartNew(() => { try { ChaosMonkey.MaybeError(0, new COMException("Fail", -2147467259)); using (var stream = DoTransfer(pageNumber, eventLoop, WiaApi.Formats.BMP)) { if (stream == null) { return (null, true); } using (Image output = Image.FromStream(stream)) { using (var result = scannedImageHelper.PostProcessStep1(output, ScanProfile)) { if (blankDetector.ExcludePage(result, ScanProfile)) { return (null, false); } ScanBitDepth bitDepth = ScanProfile.UseNativeUI ? ScanBitDepth.C24Bit : ScanProfile.BitDepth; var image = new ScannedImage(result, bitDepth, ScanProfile.MaxQuality, ScanProfile.Quality); scannedImageHelper.PostProcessStep2(image, result, ScanProfile, ScanParams, pageNumber); string tempPath = scannedImageHelper.SaveForBackgroundOcr(result, ScanParams); scannedImageHelper.RunBackgroundOcr(image, ScanParams, tempPath); return (image, false); } } } } 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 return (null, true); } }, TaskCreationOptions.LongRunning)); }
private ScannedImage ExportAsPngImage(PdfPage page, PdfDictionary imageObject, ImportParams importParams) { int width = imageObject.Elements.GetInteger(PdfImage.Keys.Width); int height = imageObject.Elements.GetInteger(PdfImage.Keys.Height); int bitsPerComponent = imageObject.Elements.GetInteger(PdfImage.Keys.BitsPerComponent); var buffer = imageObject.Stream.UnfilteredValue; Bitmap bitmap; ScanBitDepth bitDepth; switch (bitsPerComponent) { case 8: bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb); bitDepth = ScanBitDepth.C24Bit; RgbToBitmapUnmanaged(height, width, bitmap, buffer); break; case 1: bitmap = new Bitmap(width, height, PixelFormat.Format1bppIndexed); bitDepth = ScanBitDepth.BlackWhite; BlackAndWhiteToBitmapUnmanaged(height, width, bitmap, buffer); break; default: throw new NotImplementedException("Unsupported image encoding (expected 24 bpp or 1bpp)"); } using (bitmap) { bitmap.SafeSetResolution(bitmap.Width / (float)page.Width.Inch, bitmap.Height / (float)page.Height.Inch); var image = new ScannedImage(bitmap, bitDepth, true, -1); if (!importParams.NoThumbnails) { image.SetThumbnail(thumbnailRenderer.RenderThumbnail(bitmap)); } if (importParams.DetectPatchCodes) { image.PatchCode = PatchCodeDetector.Detect(bitmap); } return(image); } }
private void ProduceImage(ScannedImageSource.Concrete source, Image output, ref int pageNumber) { var results = new[] { scannedImageHelper.PostProcessStep1(output, ScanProfile) }; if (ScanProfile.DivideScanIntoTwoPages) { var result = results[0]; // Should probably detect portrait vs landscape and split appropriately but this is the // main use case. var halfHeight = result.Height / 2; var firstRect = new Rectangle(0, 0, result.Width, halfHeight); var secondRect = new Rectangle(0, halfHeight, result.Width, halfHeight); var firstPage = result.Clone(secondRect, result.PixelFormat); firstPage.RotateFlip(RotateFlipType.Rotate90FlipNone); var secondPage = result.Clone(firstRect, result.PixelFormat); secondPage.RotateFlip(RotateFlipType.Rotate90FlipNone); results = new[] { firstPage, secondPage }; result.Dispose(); } foreach (var result in results) { if (blankDetector.ExcludePage(result, ScanProfile)) { continue; } ScanBitDepth bitDepth = ScanProfile.UseNativeUI ? ScanBitDepth.C24Bit : ScanProfile.BitDepth; var image = new ScannedImage(result, bitDepth, ScanProfile.MaxQuality, ScanProfile.Quality); scannedImageHelper.PostProcessStep2(image, result, ScanProfile, ScanParams, pageNumber); string tempPath = scannedImageHelper.SaveForBackgroundOcr(result, ScanParams); result.Dispose(); scannedImageHelper.RunBackgroundOcr(image, ScanParams, tempPath); source.Put(image); pageNumber++; InitNextPageProgress(pageNumber); } }
private void ProduceImage(ScannedImageSource.Concrete source, Image output, ref int pageNumber) { using (var result = scannedImageHelper.PostProcessStep1(output, ScanProfile)) { if (blankDetector.ExcludePage(result, ScanProfile)) { return; } ScanBitDepth bitDepth = ScanProfile.UseNativeUI ? ScanBitDepth.C24Bit : ScanProfile.BitDepth; var image = new ScannedImage(result, bitDepth, ScanProfile.MaxQuality, ScanProfile.Quality); scannedImageHelper.PostProcessStep2(image, result, ScanProfile, ScanParams, pageNumber); string tempPath = scannedImageHelper.SaveForBackgroundOcr(result, ScanParams); scannedImageHelper.RunBackgroundOcr(image, ScanParams, tempPath); source.Put(image); pageNumber++; InitNextPageProgress(pageNumber); } }