Quantcast
Channel: Saraff.Twain.NET
Viewing all 419 articles
Browse latest View live

New Post: Canceling a scan through code

$
0
0
I am trying to get the user settings for a scan from the UI, and then keep these but set my own compression based on the bit depth of the image.

In order to accomplish this I am simply saving the settings from a scan on the xfer setup event and then I want to cancel the scan, and start a new one using the settings I want. I know this is convoluted but its the only thing I have come up with that supports compression for color and black and white images.

However, I have not been able to find a way to cancel a scan. I tried closing the data source but it has not been effective at canceling.

New Post: Tiff corrupted using buffered memory transfer

$
0
0
I am using the example code and the tiffs sent back are corrupted. With a disk file transfer everything works, but not when I try to switch to memory transfer.
private void Twain_MemXferEvent(object sender, Twain32.MemXferEventArgs e)
        {
            try
            {
                if (TiffMemXfer.Current != null)
                {
                    long _bitsPerRow = e.ImageInfo.BitsPerPixel * e.ImageMemXfer.Columns;
                    long _bytesPerRow = Math.Min(e.ImageMemXfer.BytesPerRow, (_bitsPerRow >> 3) + ((_bitsPerRow & 0x07) != 0 ? 1 : 0));
                    using (MemoryStream _stream = new MemoryStream())
                    {
                        for (int i = 0; i < e.ImageMemXfer.Rows; i++)
                        {
                            _stream.Position = 0;
                            _stream.Write(e.ImageMemXfer.ImageData, (int)(e.ImageMemXfer.BytesPerRow * i), (int)_bytesPerRow);
                            TiffMemXfer.Current.Strips.Add(TiffMemXfer.Current.Writer.WriteData(_stream.ToArray()));
                            TiffMemXfer.Current.StripByteCounts.Add((uint)_stream.Length);
                        }
                    }
                }
                else
                {
                    MemFileXfer.Current.Writer.Write(e.ImageMemXfer.ImageData);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("{0}: {1}\n{2}", ex.GetType().Name, ex.Message, ex.StackTrace));
            }
        }

        private void Twain_SetupMemXferEvent(object sender, Twain32.SetupMemXferEventArgs e)
        {
            try
            {
                if (this._twain.Capabilities.XferMech.GetCurrent() == TwSetupTransfer.Memory)
                {
                    if (TiffMemXfer.Current == null)
                    {
                        TiffMemXfer.Create((int)e.BufferSize);
                    }

                    #region Color Map

                    if (e.ImageInfo.PixelType == TwPixelType.Palette)
                    {
                        Twain32.ColorPalette _palette = this._twain.Palette.Get();
                        TiffMemXfer.Current.ColorMap = new ushort[_palette.Colors.Length * 3];
                        for (int i = 0; i < _palette.Colors.Length; i++)
                        {
                            TiffMemXfer.Current.ColorMap[i] = (ushort)(_palette.Colors[i].R);
                            TiffMemXfer.Current.ColorMap[i + _palette.Colors.Length] = (ushort)(_palette.Colors[i].G);
                            TiffMemXfer.Current.ColorMap[i + (_palette.Colors.Length << 1)] = (ushort)(_palette.Colors[i].B);
                        }
                    }

                    #endregion

                }
                else
                { // MemFile
                    MemFileXfer.Create((int)e.BufferSize, this._twain.Capabilities.ImageFileFormat.GetCurrent().ToString().ToLower());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("{0}: {1}\n{2}", ex.GetType().Name, ex.Message, ex.StackTrace));
            }
        }

        private void Twain_XferDone(object sender, Twain32.XferDoneEventArgs e)
        {
            if (TiffMemXfer.Current != null && TiffMemXfer.Current.Writer != null)
            {
                Twain32.ImageInfo _info = e.GetImageInfo();
                Collection<ITag> _tags = new Collection<ITag> {
                        Tag<uint>.Create(TiffTags.ImageWidth,(uint)_info.ImageWidth),
                        Tag<uint>.Create(TiffTags.ImageLength,(uint)_info.ImageLength),
                        Tag<ushort>.Create(TiffTags.SamplesPerPixel,(ushort)_info.BitsPerSample.Length),
                        Tag<ushort>.Create(TiffTags.BitsPerSample,new Func<short[],ushort[]>(val=>{
                            ushort[] _result=new ushort[_info.BitsPerSample.Length];
                            for(int i=0; i<_result.Length; i++) {
                                _result[i]=(ushort)_info.BitsPerSample[i];
                            }
                            return _result;
                        })(_info.BitsPerSample)),
                        Tag<ushort>.Create(TiffTags.Orientation,(ushort)TiffOrientation.TOPLEFT),
                        Tag<TiffCompression>.Create(TiffTags.Compression,TiffCompression.NONE),
                        Tag<TiffResolutionUnit>.Create(TiffTags.ResolutionUnit,new Func<TwUnits,TiffResolutionUnit>(val=>{
                            switch(val){
                                case TwUnits.Centimeters:
                                    return TiffResolutionUnit.CENTIMETER;
                                case TwUnits.Inches:
                                    return TiffResolutionUnit.INCH;
                                default:
                                    return TiffResolutionUnit.NONE;
                            }
                        })(this._twain.Capabilities.Units.GetCurrent())),
                        Tag<ulong>.Create(TiffTags.XResolution,(1UL<<32)|(ulong)_info.XResolution),
                        Tag<ulong>.Create(TiffTags.YResolution,(1UL<<32)|(ulong)_info.YResolution),
                        Tag<TiffHandle>.Create(TiffTags.StripOffsets,TiffMemXfer.Current.Strips.ToArray()),
                        Tag<uint>.Create(TiffTags.StripByteCounts,TiffMemXfer.Current.StripByteCounts.ToArray()),
                        Tag<uint>.Create(TiffTags.RowsPerStrip,1u),
                        //Tag<char>.Create(TiffTags.Software, Application.ProductName.ToCharArray()),
                        Tag<char>.Create(TiffTags.Model,this._twain.GetSourceProductName(this._twain.SourceIndex).ToCharArray()),
                        Tag<char>.Create(TiffTags.DateTime,DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss").PadRight(20,'\0').ToCharArray()),
                        Tag<char>.Create(TiffTags.HostComputer,Environment.MachineName.ToCharArray()),
                        Tag<ushort>.Create(TiffTags.PlanarConfiguration,(ushort)TiffPlanarConfig.CONTIG),
                        Tag<char>.Create(TiffTags.Copyright,((AssemblyCopyrightAttribute)this.GetType().Assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute),false)[0]).Copyright.ToCharArray())
                    };
                switch (_info.PixelType)
                {
                    case TwPixelType.BW:
                        _tags.Add(Tag<TiffPhotoMetric>.Create(TiffTags.PhotometricInterpretation, TiffPhotoMetric.BlackIsZero));
                        break;
                    case TwPixelType.Gray:
                        _tags.Add(Tag<TiffPhotoMetric>.Create(TiffTags.PhotometricInterpretation, TiffPhotoMetric.BlackIsZero));
                        break;
                    case TwPixelType.Palette:
                        _tags.Add(Tag<TiffPhotoMetric>.Create(TiffTags.PhotometricInterpretation, TiffPhotoMetric.Palette));
                        _tags.Add(Tag<ushort>.Create(TiffTags.ColorMap, TiffMemXfer.Current.ColorMap));
                        break;
                    case TwPixelType.RGB:
                        _tags.Add(Tag<TiffPhotoMetric>.Create(TiffTags.PhotometricInterpretation, TiffPhotoMetric.RGB));
                        break;
                    default:
                        break;
                }
                TiffMemXfer.Current.Handle = TiffMemXfer.Current.Writer.WriteImageFileDirectory(TiffMemXfer.Current.Handle, _tags);
                TiffMemXfer.Current.Strips.Clear();
                TiffMemXfer.Current.StripByteCounts.Clear();
            }
        }

        private void Twain_AcquireCompleted(object sender, EventArgs e)
        {
            if (this._twain.ImageCount > 0)
            {
                this.CurrentBitmap = this._twain.GetImage(0) as Bitmap;
            }

            if (TiffMemXfer.Current != null)
            {
                try
                {
                    TiffMemXfer.Current.Writer.BaseStream.Seek(0, SeekOrigin.Begin);
                    this.CurrentBitmap = Image.FromStream(TiffMemXfer.Current.Writer.BaseStream) as Bitmap;
                }
                finally
                {
                    TiffMemXfer.Dispose();
                }
            }

            FinalizeScan();            
        }

        private void Twain_AcquireError(object sender, Twain32.AcquireErrorEventArgs e)
        {
            FinalizeScan();

            if (e.Exception.ConditionCode != TwCC.Success)
            {
                _onError?.Invoke("Twain encountered an acquire error: " + e.Exception.ToString());
            }
        }

New Post: Сканирование через ADF

$
0
0
Добрый день. Такой вопрос - как четко проверять есть ли дуплекс,? есть ли ADF , как определить эти параметры?
как их устанавливать? В примере вы проверяете в начале доступен ли дуплекс, а если он не доступен что тогда делать? Т.е. если я допустим пытаюсь просто отсканировать на сканере без ADF - как мне устанавливать соответствующие параметры.
Еще вопрос - зачем проверяют GetCurrent? от них что-то зависит?
Пожалуйста ответьте

New Post: Canceling a scan through code

$
0
0
Hello, ghostbust555.
privatevoid _twain32_SetupMemXferEvent(object sender,Twain32.SetupMemXferEventArgs e) {
    try {
        // ...
        e.Cancel = true; // <<< it tell scanner that does not need to scan more.// ...
    } catch(Exception ex) {
        // ...
    }
}
privatevoid _twain32_MemXferEvent(object sender,Twain32.MemXferEventArgs e) {
    try {
        // ...
        e.Cancel = true; // <<< it tell scanner that does not need to scan more.// ...
    } catch(Exception ex) {
        // ...
    }
}
privatevoid _twain32_SetupFileXferEvent(object sender,Twain32.SetupFileXferEventArgs e) {
    try {
        // ...
        e.Cancel = true; // <<< it tell scanner that does not need to scan more.// ...
    } catch(Exception ex) {
        // ...
    }
}
privatevoid _twain32_FileXferEvent(object sender,Twain32.FileXferEventArgs e) {
    try {
        // ...
        e.Cancel = true; // <<< it tell scanner that does not need to scan more.// ...
    } catch(Exception ex) {
        // ...
    }
}
privatevoid _twain32_EndXfer(object sender,Twain32.EndXferEventArgs e) {
    try {
        // ...
        e.Cancel = true; // <<< it tell scanner that does not need to scan more.// ...
    } catch(Exception ex) {
        // ...
    }
}
privatevoid _twain32_XferDone(object sender,Twain32.XferDoneEventArgs e) {
    try {
        // ...
        e.Cancel = true; // <<< it tell scanner that does not need to scan more.// ...
    } catch(Exception ex) {
        // ...
    }
}

New Post: Tiff corrupted using buffered memory transfer

$
0
0
Hello, ghostbust555.
It's just a sample code. It does not cover all possible situations.

New Post: Сканирование через ADF

$
0
0
Добрый день, Aleksey1555.
Я очень советую ознакомиться с TWAIN Specification. Если кратко, то есть, к примеру, CAP_DUPLEX (Indicates whether the scanner supports duplex.), CAP_AUTOFEED (MSG_SET to TRUE to enable Source’s automatic feeding), CAP_FEEDERENABLED (If TRUE, Source’s feeder is available), и т.д..

По второй части:
DG_CONTROL / DAT_CAPABILITY operations for capability negotiation include:
  • MSG_GET Returns the Current, Default and Available settings for a capability.
  • MSG_GETCURRENT Returns the Current setting for a capability.
  • MSG_GETDEFAULT Returns the value of the Source’s preferred Default values.
  • MSG_RESET Returns the capability to its TWAIN Default (power-on) condition
    (i.e. all previous negotiation is ignored).
  • MSG_RESETALL Returns all of the current values to the default settings used when the
    driver was first installed.
  • MSG_SET Allows the application to set the Current value of a capability.
  • MSG_SETCONSTRAINT Allows the application to set the Current and Default value(s) and
    restrict the Available values to some subset of the Source’s power-on
    set of values. Sources are strongly encouraged to allow the
    application to set as many of its capabilities as possible, and further to
    reflect these changes in the Source’s user interface. This will ensure
    that the user can only select images with characteristics that are
    useful to the consuming application.

New Post: Canceling a scan through code

$
0
0
So I am not seeing the cancel property. Looking at the code I only see FileName and am getting Cancel not found on the filexfereventargs object.
public sealed class SetupFileXferEventArgs:EventArgs {

            /// <summary>
            /// Инициализирует новый экземпляр класса <see cref="SetupFileXferEventArgs"/>.
            /// </summary>
            internal SetupFileXferEventArgs() {
            }

            /// <summary>
            /// Возвращает или устанавливает имя файла изображения.
            /// </summary>
            public string FileName {
                get;
                set;
            }
        }

New Post: Canceling a scan through code

$
0
0
Hello, ghostbust555.
Obviously, you need to update to the latest version.

New Post: Сканирование через ADF

$
0
0
Ок, но.. вот странно
я пишу
tw.Capabilities.DuplexEnabled.Set(true);
после этого он сканирует с двух сторон
но если сразу написать
Twain32.Enumeration p2= tw.Capabilities.DuplexEnabled.Get();
то в p2 будет только одно значение
и оно будет OnePassDuplex
хотя очень странно сканер поддерживает ADF
и сканирует с двух сторон
а код показывает что можно сканировать только с одной стороны
где ошибка?

и еще
делаю так:
tw.Capabilities.FeederEnabled.Set(true);
tw.Capabilities.AutoFeed.Set(false);
получается должен использоваться планшет а он сканирует через автоподачу
в чем ошибка?

New Post: Сканирование через ADF

$
0
0
Добрый день, Aleksey1555.
По первой части вопроса: проблема в twain-драйвере вашего сканера. Именно он говорит, что он поддерживает только OnePassDuplex. (Такая проблема обычно у эмулирующих WIA-драйверов).
По второй части: так здесь нет ошбки, т.к. feeder - это автоподатчик, и вы его включили. AutoFeed - это непрерывное (поточное) сканирование, т.е. листы затягиваются один за одним.

New Post: Сканирование через ADF

$
0
0
Спасибо, разобрался. работает.
А у меня еще вопрос - можно какнибудь окно twain'а (если включить ShowUI=true) показать на передний план?

New Post: Сканирование через ADF

$
0
0
Добрый день, Aleksey1555.
Это вопрос к окну twain-а (источника данных). Попробуйте указать в качестве значения свойства Twain32.Parent указать свою форму.

Released: Saraff.Twain.NET Outproc Samples (Mar 30, 2016)

$
0
0
Saraff.Twain.NET Outproc Samples

Saraff.Twain.OutprocSample1 - Simple
Saraff.Twain.OutprocSample2 - Advanced
Saraff.Twain.OutprocSample3 - Advanced Async (.net 4.0)
Saraff.Twain.OutprocSample4 - Advanced Async (.net 4.6.1)


Figure 1 - Component Model of Saraff.Twain.OutprocSample


Figure 2 - Saraff.Twain.OutprocSample3

Updated Release: Saraff.Twain.NET Outproc Samples (мар 30, 2016)

$
0
0
Saraff.Twain.NET Outproc Samples

Saraff.Twain.OutprocSample1 - Simple
Saraff.Twain.OutprocSample2 - Advanced
Saraff.Twain.OutprocSample3 - Advanced Async (.net 4.0)
Saraff.Twain.OutprocSample4 - Advanced Async (.net 4.6.1)


Figure 1 - Component Model of Saraff.Twain.OutprocSample


Figure 2 - Saraff.Twain.OutprocSample3

Released: Saraff.Twain.NET WPF Samples (Mar 18, 2014)

$
0
0
Simple, Advanced and Advanced Async (.net 4.0 & .net 4.5.2) Samples


Figure 1 - Saraff.Twain.Wpf.Sample1


Figure 2 - Saraff.Twain.Wpf.Sample3

Updated Release: Saraff.Twain.NET WPF Samples (мар 18, 2014)

$
0
0
Simple, Advanced and Advanced Async (.net 4.0 & .net 4.5.2) Samples


Figure 1 - Saraff.Twain.Wpf.Sample1


Figure 2 - Saraff.Twain.Wpf.Sample3

Released: Saraff.Twain.NET Service Samples (Apr 07, 2016)

$
0
0
Saraff.Twain.NET Service Samples

Saraff.Twain.ServiceSample1 - Simple
Saraff.Twain.ServiceSample2 - Advanced
Saraff.Twain.ServiceSample3 - Advanced Async (.net 4.0)
Saraff.Twain.ServiceSample4 - Advanced Async (.net 4.6.1)


Figure 1 - Component Model of Saraff.Twain.ServiceSamples


Figure 2 - Saraff.Twain.ServiceSample3


Figure 3 - Saraff.Twain.ServiceSample3

Updated Release: Saraff.Twain.NET Service Samples (апр 07, 2016)

$
0
0
Saraff.Twain.NET Service Samples

Saraff.Twain.ServiceSample1 - Simple
Saraff.Twain.ServiceSample2 - Advanced
Saraff.Twain.ServiceSample3 - Advanced Async (.net 4.0)
Saraff.Twain.ServiceSample4 - Advanced Async (.net 4.6.1)


Figure 1 - Component Model of Saraff.Twain.ServiceSamples


Figure 2 - Saraff.Twain.ServiceSample3


Figure 3 - Saraff.Twain.ServiceSample3

Updated Wiki: Home

$
0
0
Saraff.Twain.NET is the skillful scanning component which allows you to control work of flatbed scanner, web and digital camera and any other TWAIN device from .NET environment. You can use this library in your programs written in any programming languages compatible with .NET technology.

Features:
  • TWAIN specification 1.x / 2.x compatible
  • Programming environments: .NET Framework 2.0 or higher, WPF 3.5 or higher
  • Full support for x86 and x64 platforms
  • This is a fully-managed .NET library to guarantee the fast working in .NET Framework
  • Acquire images from scanners, web or digital cameras and any other TWAIN device
  • Data source enumeration and selection
  • Control the work of Automatic Document Feeder (ADF) while scanning
  • Supports Native, Buffered Memory, Disk File and Memory File image transfer mode
  • Set up images acquisition parameters (pixel type, resolution, page size, image layout rectangle, brightness, contrast, etc)
  • Retrieve the extended image information from scanner (barcode, patch code info, etc)
  • Control advanced capabilities of TWAIN devices (rotation of images, scaling of images, filters of images, paper handling, the patch code detection and etc)
  • Save acquired images as BMP, JPEG, PNG, GIF, TIFF files
Saraff.Twain.NET was tested and has examples of use for:
  • Microsoft Visual C# 2005 / 2008 / 2010 / 2015
  • Microsoft Visual Basic - VB.NET 2005 / 2008 / 2010 / 2015
Supported frameworks: .NET 2.0 / 3.0 / 3.5 / 4.0 / 4.5 / 4.6 (including WPF)
System requirements:.NET Framework
Supported platforms:
  • Windows 2000 / XP / 2003 / Vista / 2008 / 7 / 8 / 10, 32-bit / 64-bit (See Introduction)
  • Linux (was tested on Lubuntu 14.04 LTS x86_32)
NuGet package is available.
Documentation is available

Samples:
Saraff.Twain.Sample2 on Windows 7
Figure 1 - Saraff.Twain.Sample2 on Windows 7

Updated Wiki: Home

$
0
0
Saraff.Twain.NET is the skillful scanning component which allows you to control work of flatbed scanner, web and digital camera and any other TWAIN device from .NET environment. You can use this library in your programs written in any programming languages compatible with .NET technology.

Features:
  • TWAIN specification 1.x / 2.x compatible
  • Programming environments: .NET Framework 2.0 or higher, WPF 3.5 or higher
  • Full support for x86 and x64 platforms
  • This is a fully-managed .NET library to guarantee the fast working in .NET Framework
  • Acquire images from scanners, web or digital cameras and any other TWAIN device
  • Data source enumeration and selection
  • Control the work of Automatic Document Feeder (ADF) while scanning
  • Supports Native, Buffered Memory, Disk File and Memory File image transfer mode
  • Set up images acquisition parameters (pixel type, resolution, page size, image layout rectangle, brightness, contrast, etc)
  • Retrieve the extended image information from scanner (barcode, patch code info, etc)
  • Control advanced capabilities of TWAIN devices (rotation of images, scaling of images, filters of images, paper handling, the patch code detection and etc)
  • Save acquired images as BMP, JPEG, PNG, GIF, TIFF files
Saraff.Twain.NET was tested and has examples of use for:
  • Microsoft Visual C# 2005 / 2008 / 2010 / 2015
  • Microsoft Visual Basic - VB.NET 2005 / 2008 / 2010 / 2015
Supported frameworks: .NET 2.0 / 3.0 / 3.5 / 4.0 / 4.5 / 4.6 (including WPF)
System requirements:.NET Framework
Supported platforms:
  • Windows 2000 / XP / 2003 / Vista / 2008 / 7 / 8 / 10, 32-bit / 64-bit (See Introduction)
  • Linux (was tested on Lubuntu 14.04 LTS x86_32)
NuGet package is available.
Documentation is available

Samples:
Saraff.Twain.Sample2 on Windows 7
Figure 1 - Saraff.Twain.Sample2 on Windows 7
Viewing all 419 articles
Browse latest View live