public void SaveToFileSystem(PdfReader documentReader, Twain32 scannedPages, string filePath, bool addToExistingFile) { var doc = new Document(PageSize.A4); doc.SetMargins(0, 0, 0, 0); var writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create)); doc.Open(); if (addToExistingFile) { for (int pageNumber = 1; pageNumber <= documentReader.NumberOfPages; pageNumber++) { PdfImportedPage page = writer.GetImportedPage(documentReader, pageNumber); writer.DirectContent.AddTemplate(page, 0, 0); doc.NewPage(); } } for (int i = 0; i < scannedPages.ImageCount; i++) { Image pdfImage = Image.GetInstance(scannedPages.GetImage(i), System.Drawing.Imaging.ImageFormat.Jpeg); pdfImage.ScaleAbsolute(600f, 820f); doc.Add(pdfImage); doc.NewPage(); } doc.Close(); doc.Dispose(); }
private void SetupTwain() { logger.Debug("Setup Twain"); _twain32 = new Twain32(); _twain32.TwainStateChanged += _twain_TwainStateChanged; _twain32.AcquireError += OnTwainAcquireError; if (ScanerSetup == ScanerSetup.Custom) { _twain32.SetupMemXferEvent += OnSetupMemXferEvent; _twain32.MemXferEvent += OnMemXferEvent; } _twain32.AcquireCompleted += _twain32_AcquireCompleted; logger.Debug("IsTwain2Enable = {0}", _twain32.IsTwain2Enable); _twain32.OpenDSM(); logger.Debug("IsTwain2Supported = {0}", _twain32.IsTwain2Supported); logger.Debug("Exist Sources:"); for (var i = 0; i < _twain32.SourcesCount; i++) { logger.Debug("{0}: {1}{2}", i, _twain32.GetSourceProductName(i), _twain32.IsTwain2Supported && _twain32.GetIsSourceTwain2Compatible(i)?" (TWAIN 2.x)" : string.Empty); } logger.Debug("Current Source: {0}", _twain32.GetSourceProductName(_twain32.SourceIndex)); }
public bool Acquire() { bool flag = this._twain != null; if (flag) { this._twain.Dispose(); this._twain = null; } this._twain = new Twain32(); this._twain.Parent = Control.FromHandle(this._param.HostWnd); this._twain.OpenDSM(); this._twain.ShowUI = true; this._twain.AcquireError -= new EventHandler <Twain32.AcquireErrorEventArgs>(this._twain_AcquireError); this._twain.AcquireError += new EventHandler <Twain32.AcquireErrorEventArgs>(this._twain_AcquireError); this._twain.CloseDataSource(); this._twain.SelectSource(); this.GetSetting().ResetSelectScaner = false; this._twain.EndXfer -= new EventHandler <Twain32.EndXferEventArgs>(this._twain_EndXfer); this._twain.EndXfer += new EventHandler <Twain32.EndXferEventArgs>(this._twain_EndXfer); this._twain.Acquire(); this._twain.Dispose(); this._twain = null; return(true); }
private void SetupTwain() { _twain32 = new Twain32 (); _twain32.OpenDSM(); _twain32.AcquireCompleted+=(object sender,EventArgs e) => { TotalImages = _twain32.ImageCount; for(int i = 0; i < _twain32.ImageCount; i++) { Pixbuf CurImg = WinImageToPixbuf(_twain32.GetImage(i)); if(ImageTransfer == null) {// Записываем во внутренний массив Images.Add(CurImg); } else {// Передаем через событие ImageTransferEventArgs arg = new ImageTransferEventArgs(); arg.AllImages = TotalImages; arg.Image = CurImg; ImageTransfer(this, arg); } } Console.WriteLine("DataTransferred"); }; }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (this.Handle != IntPtr.Zero) { Twain32.GlobalFree(this.Handle); this.Handle = IntPtr.Zero; } }
public TwainSource(Source source, Twain32 twain32, int index) { _source = source; _twain32 = twain32; Index = index; Name = _source.Name; }
public static byte[] Execute(Twain32 twain32, byte[] command) { var _command = TwainCommand.FromArray(command); new TwainProxy { Twain32 = twain32 }._ExecuteCore(_command); return(_command.ToArray()); }
public ScanSettingForm() { InitializeComponent(); _container = new ServiceContainer(); _container.Bind(typeof(IStreamProvider), typeof(SaraffStreamProvider)); _twain = _container.CreateInstance <Twain32>(); bindingSource.DataSource = typeof(ScanSetting); bindingSRouting.DataSource = typeof(Routing); }
/// <summary> /// Initializes a new instance of the <see cref="TwCapability"/> class. /// </summary> /// <param name="cap">The cap.</param> /// <param name="range">The range.</param> public TwCapability(TwCap cap, _TwRange range) { this.Cap = cap; this.ConType = TwOn.Range; this.Handle = Twain32.GlobalAlloc(0x42, Marshal.SizeOf(typeof(_TwRange))); IntPtr _pTwRange = Twain32.GlobalLock(Handle); Marshal.StructureToPtr(range, _pTwRange, true); Twain32.GlobalUnlock(Handle); }
public void UnInitialize() { this.ClearEvents(); bool flag = this._twain != null; if (flag) { this._twain.Dispose(); this._twain = null; this._initialized = false; } }
/// <summary> /// Initializes a new instance of the <see cref="TwCapability"/> class. /// </summary> /// <param name="cap">The cap.</param> /// <param name="array">The array.</param> /// <param name="arrayValue">The array value.</param> public TwCapability(TwCap cap, _TwArray array, object[] arrayValue) { this.Cap = cap; this.ConType = TwOn.Array; this.Handle = Twain32.GlobalAlloc(0x42, Marshal.SizeOf(typeof(_TwArray)) + (Marshal.SizeOf(arrayValue[0]) * arrayValue.Length)); IntPtr _pTwArray = Twain32.GlobalLock(Handle); Marshal.StructureToPtr(array, _pTwArray, true); for (int i = 0, _ptr = _pTwArray.ToInt32() + Marshal.SizeOf(typeof(_TwArray)); i < arrayValue.Length; i++, _ptr += Marshal.SizeOf(arrayValue[0])) { Marshal.StructureToPtr(arrayValue[i], (IntPtr)_ptr, true); } Twain32.GlobalUnlock(Handle); }
/// <summary> /// Initializes a new instance of the <see cref="TwCapability"/> class. /// </summary> /// <param name="cap">The cap.</param> /// <param name="enumeration">The enumeration.</param> /// <param name="enumerationValue">The enumeration value.</param> public TwCapability(TwCap cap, _TwEnumeration enumeration, object[] enumerationValue) { this.Cap = cap; this.ConType = TwOn.Enum; this.Handle = Twain32.GlobalAlloc(0x42, Marshal.SizeOf(typeof(_TwEnumeration)) + (Marshal.SizeOf(enumerationValue[0]) * enumerationValue.Length)); IntPtr _pTwEnumeration = Twain32.GlobalLock(Handle); Marshal.StructureToPtr(enumeration, _pTwEnumeration, true); for (int i = 0, _ptr = _pTwEnumeration.ToInt32() + Marshal.SizeOf(typeof(_TwEnumeration)); i < enumerationValue.Length; i++, _ptr += Marshal.SizeOf(enumerationValue[0])) { Marshal.StructureToPtr(enumerationValue[i], (IntPtr)_ptr, true); } Twain32.GlobalUnlock(Handle); }
private void _scannersListPreview_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { try { _twain32?.Dispose(); _twain32 = new Twain32 { ShowUI = true, IsTwain2Enable = true }; _twain32.OpenDSM(); _twain32.SourceIndex = Scanners.IndexOf(SelectedScanner); _twain32.OpenDataSource(); _twain32.EndXfer += _twain32_EndXfer; _twain32.AcquireCompleted += _twain32_AcquireCompleted; _twain32.AcquireError += _twain32_AcquireError; _twain32.MemXferEvent += _twain32_MemXferEvent; _twain32.Acquire(); if (_scannedImage != null) { SaveImage(); } Environment.ExitCode = (int)ExitCodes.ExitCode.SUCCESS; CustomMessageBox.Show($"Save photo: {Path.GetFileName(_filePath)}\n{_destinationPath}", "Succes", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); } catch (Exception ex) { var messagebox = CustomMessageBox.Show(ex.Message, "Scanner Error!", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Error); if (messagebox == System.Windows.Forms.DialogResult.Yes) { Environment.ExitCode = (int)ExitCodes.ExitCode.ERROR_DEVICE_UNREACHABLE; } } finally { _twain32?.CloseDSM(); _twain32?.CloseDataSource(); _twain32.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); this.Close(); } }
/// <summary> /// Initializes a new instance of the <see cref="TwCapability"/> class. /// </summary> /// <param name="cap">The cap.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> public TwCapability(TwCap cap, int value, TwType type) { this.Cap = cap; this.ConType = TwOn.One; _TwOneValue _value = new _TwOneValue() { ItemType = type, Item = value }; this.Handle = Twain32.GlobalAlloc(0x42, Marshal.SizeOf(typeof(_TwOneValue))); IntPtr _pTwOneValue = Twain32.GlobalLock(Handle); Marshal.StructureToPtr(_value, _pTwOneValue, true); Twain32.GlobalUnlock(Handle); }
public NewScanForm() { InitializeComponent(); _container = new ServiceContainer(); _container.Bind(typeof(IStreamProvider), typeof(SaraffStreamProvider)); _twain = _container.CreateInstance <Twain32>(); _twain.EndXfer += EndXfer; _twain.AcquireCompleted += AcquireCompleted; _imageIndex = 0; _images = new List <Image>(); _scannedItems = new List <ScannedImage>(); _settingsManager = new ScanSettingsManager(); _previewing = false; _closingWindow = false; }
public static void PLOCRtwain_TwainStateChanged(object sender, Twain32.TwainStateEventArgs e) { using (Twain32 PLOCRtwain = new Twain32()) { try { // ... _isDataSourceOpen = (e.TwainState & Twain32.TwainStateFlag.DSOpen) != 0; // ... MessageBox.Show("twain 상태가 변경되었습니다."); } catch (Exception ex) { // ... } } }
public static void PLOCRtwain_TwainStateChanged(object sender, Twain32.TwainStateEventArgs e) { using (Twain32 PLOCRtwain = new Twain32()) { try { // ... _isDataSourceOpen = (e.TwainState&Twain32.TwainStateFlag.DSOpen) != 0; // ... MessageBox.Show("twain 상태가 변경되었습니다."); } catch (Exception ex) { // ... } } }
public static IEnumerable <byte[]> Execute(Twain32 twain32, IEnumerable <byte[]> commands) { var _proxy = new TwainProxy { Twain32 = twain32 }; foreach (var _data in commands) { for (var _command = TwainCommand.FromArray(_data); _command != null;) { _proxy._ExecuteCore(_command); yield return(_command.ToArray()); break; } } yield break; }
/// <summary> /// Create instance of a XDsm class. /// </summary> /// <param name="twain32">Instance of the Twain32 class.</param> /// <param name="isOwns">If set to <c>true</c> is owner of instance of the Twain32 class.</param> /// <returns></returns> public static XDsm Create(Twain32 twain32, bool isOwns = false) { XDsm _dsm = null; try { return(_dsm = new XDsm { _twain32 = twain32, _isOwns = isOwns }); } finally { twain32.EndXfer += _dsm._EndXfer; twain32.XferDone += _dsm._XferDone; twain32.SetupMemXferEvent += _dsm._SetupMemXferEvent; twain32.MemXferEvent += _dsm._MemXferEvent; twain32.SetupFileXferEvent += _dsm._SetupFileXferEvent; twain32.FileXferEvent += _dsm._FileXferEvent; twain32.AcquireCompleted += _dsm._AcquireCompleted; twain32.AcquireError += _dsm._AcquireError; } }
public Scanner(HWDeviceDesciption selectedScanner) { this.selectedScanner = selectedScanner; twain = new Twain32(); twain.IsTwain2Enable = true; // set twain settings twain.DisableAfterAcquire = true; twain.ShowUI = false; if (this.ParentWindowHandle != IntPtr.Zero) { var parentWnd = new NativeWindow(); parentWnd.AssignHandle(this.ParentWindowHandle); twain.Parent = parentWnd; } // add event handlers twain.EndXfer += endXferEventHandler; twain.AcquireCompleted += acquireCompletedEventHandler; twain.AcquireError += acquireErrorEventHandler; }
public IEnumerable <HWDeviceDesciption> GetDevices() { var twain = new Twain32(); var isDsmOpened = false; try { //twain.OpenDataSource(); isDsmOpened = twain.OpenDSM(); if (twain.IsTwain2Supported) { twain.IsTwain2Enable = true; } } catch (Exception ex) { logger.Error(ex); } if (isDsmOpened) { for (int i = 0; i < twain.SourcesCount; i++) { yield return(new HWDeviceDesciption { Device = DeviceType.Scanner, Name = twain.GetSourceProductName(i), DeviceId = i.ToString() }); } } if (twain != null) { twain.CloseDataSource(); twain.CloseDSM(); twain.Dispose(); } yield break; }
public static void timer1_Tick(object sender, EventArgs e) { using (Twain32 PLOCRtwain = new Twain32()) { try { // MessageBox.Show("타이머 작동 확인용 창"); // if (_isDataSourceOpen) // { // ... var _isFeederLoaded = (bool)PLOCRtwain.GetCurrentCap(TwCap.FeederLoaded); // ... MessageBox.Show("처방전이 올려졌습니다."); // } } catch (Exception ex) { // ... } } }
private void LoadParametes() { try { _twain32 = new Twain32 { ShowUI = true, IsTwain2Enable = true }; _twain32.OpenDSM(); #region GetScanners for (int i = 0; i < _twain32.SourcesCount; i++) { _scanners.Add(_twain32.GetSourceProductName(i)); } #endregion GetScanners if (Scanners.Count > 0) { SelectedScanner = Scanners.FirstOrDefault(); } } catch (Exception ex) { var messagebox = CustomMessageBox.Show(ex.Message, "Error!", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Error); if (messagebox == System.Windows.Forms.DialogResult.Yes) { _twain32?.CloseDSM(); _twain32?.CloseDataSource(); _twain32.Dispose(); Environment.ExitCode = (int)ExitCodes.ExitCode.ERROR_DEVICE_UNREACHABLE; this.Close(); } } }
/// <summary> /// Возвращает результат для указаной возможности. /// </summary> /// <returns>Экземпляр TwArray, TwEnumeration, _TwRange или _TwOneValue.</returns> public object GetValue() { IntPtr _handle = Twain32.GlobalLock(this.Handle); try { switch (this.ConType) { case TwOn.Array: _TwArray _res = Marshal.PtrToStructure(_handle, typeof(_TwArray)) as _TwArray; switch (_res.ItemType) { case TwType.Int8: case TwType.UInt8: { byte[] _array = new byte[_res.NumItems]; Marshal.Copy((IntPtr)(_handle.ToInt32() + Marshal.SizeOf(typeof(_TwArray))), _array, 0, _array.Length); return(new TwArray <byte>(_res, _array)); } case TwType.Int16: case TwType.UInt16: case TwType.Bool: { short[] _array = new short[_res.NumItems]; Marshal.Copy((IntPtr)(_handle.ToInt32() + Marshal.SizeOf(typeof(_TwArray))), _array, 0, _array.Length); return(new TwArray <short>(_res, _array)); } case TwType.Int32: case TwType.UInt32: case TwType.Fix32: { int[] _array = new int[_res.NumItems]; Marshal.Copy((IntPtr)(_handle.ToInt32() + Marshal.SizeOf(typeof(_TwArray))), _array, 0, _array.Length); return(new TwArray <int>(_res, _array)); } } break; case TwOn.Enum: _TwEnumeration _res2 = Marshal.PtrToStructure(_handle, typeof(_TwEnumeration)) as _TwEnumeration; switch (_res2.ItemType) { case TwType.Int8: case TwType.UInt8: { byte[] _array = new byte[_res2.NumItems]; Marshal.Copy((IntPtr)(_handle.ToInt32() + Marshal.SizeOf(typeof(_TwEnumeration))), _array, 0, _array.Length); return(new TwEnumeration <byte>(_res2, _array)); } case TwType.Int16: case TwType.UInt16: case TwType.Bool: { short[] _array = new short[_res2.NumItems]; Marshal.Copy((IntPtr)(_handle.ToInt32() + Marshal.SizeOf(typeof(_TwEnumeration))), _array, 0, _array.Length); return(new TwEnumeration <short>(_res2, _array)); } case TwType.Int32: case TwType.UInt32: case TwType.Fix32: { int[] _array = new int[_res2.NumItems]; Marshal.Copy((IntPtr)(_handle.ToInt32() + Marshal.SizeOf(typeof(_TwEnumeration))), _array, 0, _array.Length); return(new TwEnumeration <int>(_res2, _array)); } } break; case TwOn.Range: return(Marshal.PtrToStructure(_handle, typeof(_TwRange))); case TwOn.One: return(Marshal.PtrToStructure(_handle, typeof(_TwOneValue))); } return(null); } finally { IntPtr _res2 = Twain32.GlobalFree(_handle); } }
public void SaveDocument(string filename, string documentType, string docDescription, string archiveFolder, bool addToExistingFile, DatabaseManager databaseManager, PdfReader documentReader, Twain32 scannedPages) { var newFileDirectory = this.CreateDirectory(archiveFolder, documentType); var filePath = $"{newFileDirectory}\\{filename}.pdf"; var dateOfCreation = DateTime.Now; var newDocument = new ScannedDocument(filename, docDescription, documentType, dateOfCreation, filePath); databaseManager.InsertDocument(newDocument); var saveDialog = new SaveFileDialog(); saveDialog.InitialDirectory = newFileDirectory; saveDialog.Filter = "PDF File|*.pdf"; saveDialog.FileName = filename; if (saveDialog.ShowDialog() == DialogResult.OK) { this.SaveToFileSystem(documentReader, scannedPages, filePath, addToExistingFile); } }
void OnMemXferEvent(object sender, Twain32.MemXferEventArgs e) { try { logger.Debug("On MemXfer Event {0}", this.stream.Position); //FIXME Некорректно работает с черно белыми изображениями на нашем сканере(нужно проверить) int _bytesPerPixel=e.ImageInfo.BitsPerPixel>>3; for(int i=0,_rowOffset=0; i<e.ImageMemXfer.Rows; i++,_rowOffset+=(int)e.ImageMemXfer.BytesPerRow) { for(int ii=0,_colOffset=0; ii<e.ImageMemXfer.Columns; ii++,_colOffset+=_bytesPerPixel) { switch(e.ImageInfo.BitsPerPixel) { case 1: for(int _mask=1; (_mask&0xff)!=0&&ii<e.ImageMemXfer.Columns; _mask<<=1,ii++) { this.stream.WriteByte((e.ImageMemXfer.ImageData[_rowOffset+_colOffset]&_mask)!=0?byte.MaxValue:byte.MinValue); } _colOffset++; ii--; break; case 8: case 24: if(e.ImageInfo.PixelType==TwPixelType.Palette) { System.Drawing.Color _color=this.palette.Colors[e.ImageMemXfer.ImageData[_rowOffset+_colOffset]]; this.stream.Write(new byte[] { _color.R,_color.G,_color.B },0,3); } else { this.stream.Write(e.ImageMemXfer.ImageData,_rowOffset+_colOffset,_bytesPerPixel); } break; } } } OnPulse(e.ImageInfo.BitsPerPixel * e.ImageInfo.ImageLength * e.ImageInfo.ImageWidth / 8, (int)stream.Position); } catch(Exception ex) { logger.Error (ex, "Ошибка при получении изображения."); throw ex; } }
static void Main(string[] args) { isSilenced = !(indexOf(args, "-s") >= 0); var d = indexOf(args, "-d"); if (d >= 0 && args.Length > d + 1) { float.TryParse(args[d + 1], out dpi); } var p = indexOf(args, "-p"); if (p >= 0 && args.Length > p + 1) { string val = args[p + 1].ToUpper(); if (val == "BW") { pt = (TwPixelType)0; } if (val == "Gray") { pt = (TwPixelType)1; } if (val == "RGB") { pt = (TwPixelType)2; } if (val == "Palette") { pt = (TwPixelType)3; } if (val == "CMY") { pt = (TwPixelType)4; } if (val == "CMYK") { pt = (TwPixelType)5; } if (val == "YUV") { pt = (TwPixelType)6; } if (val == "YUVK") { pt = (TwPixelType)7; } if (val == "CIEXYZ") { pt = (TwPixelType)8; } if (val == "LAB") { pt = (TwPixelType)9; } if (val == "SRGB") { pt = (TwPixelType)10; } if (val == "SCRGB") { pt = (TwPixelType)11; } if (val == "INFRARED") { pt = (TwPixelType)16; } } try { using (Twain32 twain = new Twain32()) { var _asm = twain.GetType().Assembly; WriteMessage("{1} {2}{0}{3}{0}", Environment.NewLine, ((AssemblyTitleAttribute)_asm.GetCustomAttributes(typeof(AssemblyTitleAttribute), false)[0]).Title, ((AssemblyFileVersionAttribute)_asm.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)[0]).Version, ((AssemblyCopyrightAttribute)_asm.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false)[0]).Copyright); twain.ShowUI = false; WriteMessage("ShowUI: {0}", twain.ShowUI ? "true" : "false"); WriteMessage("IsTwain2Enable {0}: ", twain.IsTwain2Enable ? "[Y/n]" : "[y/N]"); if (isSilenced) { for (var _res = Console.ReadLine().Trim().ToUpper(); !string.IsNullOrEmpty(_res);) { twain.IsTwain2Enable = _res == "Y"; break; } } else { twain.IsTwain2Enable = false; } WriteMessage("IsTwain2Enable: {0}", twain.IsTwain2Enable ? "true" : "false"); twain.OpenDSM(); WriteMessage("Select Data Source:"); if (isSilenced) { for (var i1 = 0; i1 < twain.SourcesCount; i1++) { WriteMessage("{0}: {1}{2}", i1, twain.GetSourceProductName(i1), twain.IsTwain2Supported && twain.GetIsSourceTwain2Compatible(i1) ? " (TWAIN 2.x)" : string.Empty); } } WriteMessage("[{0}]: ", twain.SourceIndex); if (isSilenced) { for (var _res = Console.ReadLine().Trim(); !string.IsNullOrEmpty(_res);) { twain.SourceIndex = Convert.ToInt32(_res); break; } } else { twain.SourceIndex = 0; } WriteMessage(string.Format("Data Source: {0}", twain.GetSourceProductName(twain.SourceIndex))); twain.OpenDataSource(); WriteMessage("Select Resolution:"); var _resolutions = twain.Capabilities.XResolution.Get(); if (isSilenced) { for (var i1 = 0; i1 < _resolutions.Count; i1++) { WriteMessage(true, "{0}: {1} dpi", i1, _resolutions[i1]); } } WriteMessage("[{0}]: ", _resolutions.CurrentIndex); if (isSilenced) { for (var _res = Console.ReadLine().Trim(); !string.IsNullOrEmpty(_res);) { var _val = (float)_resolutions[Convert.ToInt32(_res)]; twain.Capabilities.XResolution.Set(_val); twain.Capabilities.YResolution.Set(_val); break; } } else { twain.Capabilities.XResolution.Set(dpi); twain.Capabilities.YResolution.Set(dpi); } WriteMessage("Resolution: {0}", twain.Capabilities.XResolution.GetCurrent()); WriteMessage("Select Pixel Type:"); var _pixels = twain.Capabilities.PixelType.Get(); if (isSilenced) { for (var i1 = 0; i1 < _pixels.Count; i1++) { WriteMessage("{0}: {1}", i1, _pixels[i1]); } } WriteMessage("[{0}]: ", _pixels.CurrentIndex); if (isSilenced) { for (var _res = Console.ReadLine().Trim(); !string.IsNullOrEmpty(_res);) { var _val = (TwPixelType)_pixels[Convert.ToInt32(_res)]; twain.Capabilities.PixelType.Set(_val); break; } } else { twain.Capabilities.PixelType.Set(pt); } WriteMessage(string.Format("Pixel Type: {0}", twain.Capabilities.PixelType.GetCurrent())); twain.EndXfer += (object sender, Twain32.EndXferEventArgs e) => { try { var _file = Path.Combine("", Path.ChangeExtension(Path.GetFileName(Path.GetTempFileName()), ".jpg")); e.Image.Save(_file, ImageFormat.Jpeg); WriteMessage(true, "Saved in: {0}", _file); e.Image.Dispose(); } catch (Exception ex) { WriteMessage("{0}: {1}{2}{3}{2}", ex.GetType().Name, ex.Message, Environment.NewLine, ex.StackTrace); } }; twain.AcquireCompleted += (sender, e) => { try { WriteMessage("Acquire Completed."); } catch (Exception ex) { Program.WriteException(ex); } }; twain.AcquireError += (object sender, Twain32.AcquireErrorEventArgs e) => { try { WriteMessage("Acquire Error: ReturnCode = {0}; ConditionCode = {1};", e.Exception.ReturnCode, e.Exception.ConditionCode); Program.WriteException(e.Exception); } catch (Exception ex) { Program.WriteException(ex); } }; twain.Acquire(); } } catch (Exception ex) { WriteException(ex); } if (isSilenced) { Console.WriteLine("{0}{1}", Environment.NewLine, "Press any key to exit..."); Console.ReadKey(); } }
void OnTwainAcquireError(object sender, Twain32.AcquireErrorEventArgs e) { logger.Error (e.Exception, "Ошибка в процессе сканирования"); this.Close (); }
void OnSetupMemXferEvent(object sender, Twain32.SetupMemXferEventArgs e) { if (stream != null) FinishImageTransfer (); logger.Debug("SetupMemXfer size={0}B", e.ImageInfo.BitsPerPixel * e.ImageInfo.ImageLength * e.ImageInfo.ImageWidth / 8); try { stream = new MemoryStream((int)e.BufferSize); var _writer=new BinaryWriter(this.stream); switch(e.ImageInfo.BitsPerPixel) { case 1: if(e.ImageInfo.PixelType==TwPixelType.Palette) { _writer.Write(Encoding.ASCII.GetBytes("P6\n")); this.palette=this._twain32.Palette.Get(); } else { _writer.Write(Encoding.ASCII.GetBytes("P5\n")); } break; case 3: _writer.Write(Encoding.ASCII.GetBytes("P6\n")); break; default: _writer.Write(Encoding.ASCII.GetBytes("PX\n")); break; } _writer.Write(Encoding.ASCII.GetBytes(string.Format("# (C) SARAFF SOFTWARE 2013.\n{0} {1}\n{2}\n",e.ImageInfo.ImageWidth,e.ImageInfo.ImageLength,byte.MaxValue))); OnPulse(e.ImageInfo.BitsPerPixel * e.ImageInfo.ImageLength * e.ImageInfo.ImageWidth / 8, (int)stream.Position); } catch(Exception ex) { logger.Error (ex, "Ошибка при настройке буфера приема."); throw ex; } }
private void _twain32_EndXfer(object sender,Twain32.EndXferEventArgs e) { logger.Debug("EndXfer fired"); if(e.Image!=null) { Pixbuf CurImg = WinImageToPixbuf(e.Image); e.Image.Dispose(); if(ImageTransfer == null) {// Записываем во внутренний массив Images.Add(CurImg); } else {// Передаем через событие ImageTransferEventArgs arg = new ImageTransferEventArgs(); arg.AllImages = TotalImages; arg.Image = CurImg; ImageTransfer(this, arg); } } }
private void SetupTwain() { logger.Debug("Setup Twain"); _twain32 = new Twain32 (); _twain32.TwainStateChanged += _twain_TwainStateChanged; _twain32.AcquireError += OnTwainAcquireError; _twain32.SetupMemXferEvent += OnSetupMemXferEvent; _twain32.MemXferEvent += OnMemXferEvent; _twain32.AcquireCompleted += _twain32_AcquireCompleted; logger.Debug ("IsTwain2Enable = {0}", _twain32.IsTwain2Enable); _twain32.OpenDSM(); logger.Debug ("IsTwain2Supported = {0}", _twain32.IsTwain2Supported); logger.Debug ("Exist Sources:"); for(var i=0; i<_twain32.SourcesCount; i++) { logger.Debug("{0}: {1}{2}", i, _twain32.GetSourceProductName(i), _twain32.IsTwain2Supported&&_twain32.GetIsSourceTwain2Compatible(i)?" (TWAIN 2.x)" : string.Empty); } logger.Debug ("Current Source: {0}", _twain32.GetSourceProductName (_twain32.SourceIndex)); }
//public static bool _isDataSourceOpen = false; //public static void _twain_TwainStateChanged(object sender, Twain32.TwainStateEventArgs e) //{ // try // { // // ... // _isDataSourceOpen = (e.TwainState & Twain32.TwainStateFlag.DSOpen) != 0; // // ... // MessageBox.Show("twain 상태가 변경되었습니다."); // } // catch (Exception ex) // { // // ... // } //} //public static void timer1_Tick(object sender, EventArgs e) //{ // using (Twain32 PLOCRtwain = new Twain32()) // { // try // { // // MessageBox.Show("타이머 작동 확인용 창"); // // if (_isDataSourceOpen) // // { // // ... // var _isFeederLoaded = (bool)PLOCRtwain.GetCurrentCap(TwCap.FeederLoaded); // // ... // MessageBox.Show("처방전이 올려졌습니다."); // // } // } // catch (Exception ex) // { // // ... // } // } //} public static Bitmap scanImage() { Bitmap scanedImage = null; try { using (Twain32 PLOCRtwain = new Twain32()) { PLOCRtwain.IsTwain2Enable = true; // DSM(data source manager 를 열기 전에 twain 2.0 버전이상을 쓰겠다고 지정해야함 // PLOCRtwain.Dispose(); // OpenDSM() 에서 보호된 메모리 쓰려고 하는 오류가 생겨서.... 원인을 찾아보고 이 코드는 안 쓰는 방향으로 해야함. PLOCRtwain.OpenDSM(); // PLOCRtwain.SourceIndex = 0; PLOCRtwain.OpenDataSource(); // PLOCRtwain.GetResolutions(); PLOCRtwain.Capabilities.XResolution.Set(300f); // 스캔 해상도 300dpi 로 지정하고, float 로 넣어야 하므로 300f 로 입력 PLOCRtwain.Capabilities.YResolution.Set(300f); PLOCRtwain.ShowUI = false; // twain 사용자 인터페이서를 보이지 않도록 하고 try { if ((PLOCRtwain.IsCapSupported(TwCap.AutoScan) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.AutoScan, false); // 한장씩 처리하기 위해 aucoscan 을 false 로 세팅 } if ((PLOCRtwain.IsCapSupported(TwCap.AutoFeed) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.AutoFeed, false); // 한장 처리하고 대기하기 위해 autofed 를 false 로 세팅 } if ((PLOCRtwain.IsCapSupported(TwCap.DuplexEnabled) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.DuplexEnabled, true); } PLOCRtwain.AcquireCompleted += (sender, e) => // 이 부분이 Acquire 보다 먼저 나와야 함, 한참 헤멨음 { // scanImage(); // string _file_name = string.Format("{0}\\ScanImage.jpg", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)); scanedImage = (Bitmap)PLOCRtwain.GetImage(0); File.Delete(@"C:\Program Files\PLOCR\prescription.png"); scanedImage.Save(@"C:\Program Files\PLOCR\prescription.png"); }; if ((PLOCRtwain.IsCapSupported(TwCap.FeederEnabled) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.FeederEnabled, true); // MessageBox.Show("feederenabled"); var _isFeederLoaded = false; while (_isFeederLoaded == false) // 처방전이 ADF 트레이에 올라올 때까지 무한루프를 돌리며 대기, 좋은 방법은 아닌 것 같음 { // MessageBox.Show("feederloaded 루프 안"); _isFeederLoaded = (bool)PLOCRtwain.GetCurrentCap(TwCap.FeederLoaded); // 반복해서 현재 feederloaded 상태를 감시 if (_isFeederLoaded == true) // 처방전이 올라왔으면 바로 읽어들이기 시작 { /////////////////// 처방전 스캔 시작 /////////////////////////// //splashPres fmPres = new splashPres(); //fmPres.Owner = DataEdit.ActiveForm; // child form 을 알리고 //fmPres.Show(); // 스캔중 화면을 띄우고 PLOCRtwain.Acquire(); //fmPres.Close(); // 스캔중 화면 닫고 ///////////////// 처방전 스캔 끝 /////////////////////////// // PLOCRtwain.Dispose(); // twain 닫고 // PLOCRtwain.CloseDataSource(); // PLOCRtwain.CloseDSM(); } else if (_isFeederLoaded == false) { } } } // PLOCRtwain.Acquire(); } catch (Exception) { Console.WriteLine("스캐너 옵션을 가져오지 못했습니다."); System.Diagnostics.Process.GetCurrentProcess().Kill(); // 프로그램 강제 종료 } //PLOCRtwain.CloseDataSource(); //PLOCRtwain.CloseDSM(); } } catch (TwainException) { Console.WriteLine("스캔 오류가 발생했습니다."); System.Diagnostics.Process.GetCurrentProcess().Kill(); // 프로그램 강제 종료 } return(scanedImage); }
public static Bitmap scanImage() { Bitmap scanedImage = null; try { using (Twain32 PLOCRtwain = new Twain32()) { PLOCRtwain.IsTwain2Enable = true; // DSM(data source manager 를 열기 전에 twain 2.0 버전이상을 쓰겠다고 지정해야함 // PLOCRtwain.Dispose(); // OpenDSM() 에서 보호된 메모리 쓰려고 하는 오류가 생겨서.... 원인을 찾아보고 이 코드는 안 쓰는 방향으로 해야함. PLOCRtwain.OpenDSM(); // PLOCRtwain.SourceIndex = 0; PLOCRtwain.OpenDataSource(); // PLOCRtwain.GetResolutions(); PLOCRtwain.Capabilities.XResolution.Set(300f); // 스캔 해상도 300dpi 로 지정하고, float 로 넣어야 하므로 300f 로 입력 PLOCRtwain.Capabilities.YResolution.Set(300f); PLOCRtwain.ShowUI = false; // twain 사용자 인터페이서를 보이지 않도록 하고 try { if ((PLOCRtwain.IsCapSupported(TwCap.AutoScan) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.AutoScan, false); // 한장씩 처리하기 위해 aucoscan 을 false 로 세팅 } if ((PLOCRtwain.IsCapSupported(TwCap.AutoFeed) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.AutoFeed, false); // 한장 처리하고 대기하기 위해 autofed 를 false 로 세팅 } if ((PLOCRtwain.IsCapSupported(TwCap.DuplexEnabled) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.DuplexEnabled, true); } PLOCRtwain.AcquireCompleted += (sender, e) => // 이 부분이 Acquire 보다 먼저 나와야 함, 한참 헤멨음 { // scanImage(); // string _file_name = string.Format("{0}\\ScanImage.jpg", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)); scanedImage = (Bitmap)PLOCRtwain.GetImage(0); File.Delete(@"C:\Program Files\PLOCR\prescription.png"); scanedImage.Save(@"C:\Program Files\PLOCR\prescription.png"); }; if ((PLOCRtwain.IsCapSupported(TwCap.FeederEnabled) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.FeederEnabled, true); // MessageBox.Show("feederenabled"); var _isFeederLoaded = false; while (_isFeederLoaded == false) // 처방전이 ADF 트레이에 올라올 때까지 무한루프를 돌리며 대기, 좋은 방법은 아닌 것 같음 { // MessageBox.Show("feederloaded 루프 안"); _isFeederLoaded = (bool)PLOCRtwain.GetCurrentCap(TwCap.FeederLoaded); // 반복해서 현재 feederloaded 상태를 감시 if (_isFeederLoaded == true) // 처방전이 올라왔으면 바로 읽어들이기 시작 { ///////////////// 처방전 스캔 시작 /////////////////////////// splashPres fmPres = new splashPres(); fmPres.Owner = DataEdit.ActiveForm; // child form 을 알리고 fmPres.Show(); // 스캔중 화면을 띄우고 PLOCRtwain.Acquire(); fmPres.Close(); // 스캔중 화면 닫고 ///////////////// 처방전 스캔 끝 /////////////////////////// // PLOCRtwain.Dispose(); // twain 닫고 // PLOCRtwain.CloseDataSource(); // PLOCRtwain.CloseDSM(); } else if (_isFeederLoaded == false) { } } } // PLOCRtwain.Acquire(); } catch (Exception) { Console.WriteLine("스캐너 옵션을 가져오지 못했습니다."); System.Diagnostics.Process.GetCurrentProcess().Kill(); // 프로그램 강제 종료 } //PLOCRtwain.CloseDataSource(); //PLOCRtwain.CloseDSM(); } } catch (TwainException) { Console.WriteLine("스캔 오류가 발생했습니다."); System.Diagnostics.Process.GetCurrentProcess().Kill(); // 프로그램 강제 종료 } return scanedImage; }
private void _twain_TwainStateChanged(object sender,Twain32.TwainStateEventArgs e) { logger.Debug("Handle TwainState"); if((e.TwainState&Twain32.TwainStateFlag.DSEnabled)==0&&this._isEnable) { this._isEnable=false; // <<< scaning finished (or closed) if (stream != null) FinishImageTransfer (); logger.Debug ("Сканирование закончено..."); _twain32.CloseDataSource (); } this._isEnable=(e.TwainState&Twain32.TwainStateFlag.DSEnabled)!=0; while (Gtk.Application.EventsPending ()) Gtk.Application.RunIteration (); }
public TwainScannerManager() { _sources = new List <TwainSource>(); _twain32 = new Twain32(); _twain32.AppProductName = "Twain@Web"; }
public static void Handler(Twain32 twain32) { try { #region Method Handler Action _method = () => { var _result = TwainProxy.Execute(twain32, Convert.FromBase64String(Console.In.ReadLine())); Console.Out.WriteLine(Separators.BeginResponse); Console.Out.WriteLine(Convert.ToBase64String(_result)); Console.Out.WriteLine(Separators.EndResponse); }; #endregion #region Event Handler Action <EventHandlerTwainCommand> _event = command => { Console.Out.WriteLine(Separators.BeginEvent); try { Console.Out.WriteLine(Convert.ToBase64String(command.ToArray())); for (string _responce = null; !string.IsNullOrEmpty(_responce = Console.In.ReadLine());) { if (_responce == Separators.BeginRequest) { _method(); continue; } var _res = ((EventHandlerTwainCommand)TwainCommand.FromArray(Convert.FromBase64String(_responce))).Args; foreach (var _property in _res.GetType().GetProperties()) { var _setter = _property.GetSetMethod(); if (_setter != null) { _setter.Invoke(command.Args, new object[] { _property.GetValue(_res, null) }); } } break; } } finally { Console.Out.WriteLine(Separators.EndEvent); } }; #endregion #region AcquireError twain32.AcquireError += (sender, e) => { _event(new EventHandlerTwainCommand { Member = typeof(Twain32).GetEvent(Twain32Events.AcquireError), Args = e }); }; #endregion #region XferDone twain32.XferDone += (sender, e) => { var _args = new Twain32.SerializableCancelEventArgs { Cancel = e.Cancel }; _event(new EventHandlerTwainCommand { Member = typeof(Twain32).GetEvent(Twain32Events.XferDone), Args = _args }); e.Cancel = _args.Cancel; }; #endregion #region EndXfer twain32.EndXfer += (sender, e) => { _event(new EventHandlerTwainCommand { Member = typeof(Twain32).GetEvent(Twain32Events.EndXfer), Args = e }); }; #endregion #region SetupMemXferEvent twain32.SetupMemXferEvent += (sender, e) => { _event(new EventHandlerTwainCommand { Member = typeof(Twain32).GetEvent(Twain32Events.SetupMemXferEvent), Args = e }); }; #endregion #region MemXferEvent twain32.MemXferEvent += (sender, e) => { _event(new EventHandlerTwainCommand { Member = typeof(Twain32).GetEvent(Twain32Events.MemXferEvent), Args = e }); }; #endregion #region SetupFileXferEvent twain32.SetupFileXferEvent += (sender, e) => { _event(new EventHandlerTwainCommand { Member = typeof(Twain32).GetEvent(Twain32Events.SetupFileXferEvent), Args = e }); }; #endregion #region FileXferEvent twain32.FileXferEvent += (sender, e) => { _event(new EventHandlerTwainCommand { Member = typeof(Twain32).GetEvent(Twain32Events.FileXferEvent), Args = e }); }; #endregion #region TwainStateChanged twain32.TwainStateChanged += (sender, e) => { _event(new EventHandlerTwainCommand { Member = typeof(Twain32).GetEvent(Twain32Events.TwainStateChanged), Args = e }); }; #endregion #region AcquireCompleted twain32.AcquireCompleted += (sender, e) => { _event(new EventHandlerTwainCommand { Member = typeof(Twain32).GetEvent(Twain32Events.AcquireCompleted), Args = e }); }; #endregion Console.Out.WriteLine(Separators.Ready); for (string _query = null; !string.IsNullOrEmpty(_query = Console.In.ReadLine()) && _query != Separators.End;) { if (_query == Separators.BeginRequest) { _method(); } } } catch (Exception ex) { try { Console.Error.WriteLine(Separators.BeginException); for (var _ex = ex; _ex != null; _ex = _ex.InnerException) { Console.Error.WriteLine("{0}: {1}", _ex.GetType().Name, _ex.Message); Console.Error.WriteLine(_ex.StackTrace); Console.Error.WriteLine(); } Console.Error.WriteLine(Separators.EndException); } catch { } } }
static TwainFactory() { _twain = new Twain32(); _twain.ShowUI = false; _twain.OpenDSM(); }