Mike
Mike

Reputation: 533

Scanning using nTwain

I do perform a scan using nTwain lib from NuGet. I catch the DataTransferred event to save the result image. What I have in a result is some ImageInfo and null byte[] massive of information.

Is anyone aware of this library and can tell me if I am doing something wrong?

void session_DataTransferred(object sender, NTwain.DataTransferredEventArgs e)
{
  Image img = ImageFromBytes(e.MemoryData);
  myDS.Close();
  session.Close();
}

But the e comes only with ImageInfo.

Update

Argument screenshot if useful ...

enter image description here

Upvotes: 0

Views: 6769

Answers (1)

Harbie
Harbie

Reputation: 100

For NTwain, you should have more than just ImageInfo for that event. Specifically, e should have ImageInfo, MemData, and NativeData as you are showing in the screenshot.

I haven't done a whole lot with it but what I do in a console utility is to check if e.NativeData != IntPtr.Zero and pull a bitmap from the DIB pointer (Windows, it is a TIFF for Linux) . For this purpose, I am using another dependency CommonWin32.dll. I believe this is a similar method to the examples included in NTwain's starting solution package (look under Tests for a sample Console, WinForm, and WPF project).

If I want to save out a different file type, I do a encoding at that point. You can save a System.Drawing.Image with a given encoding. Obviously, that could be alot better (set the type and compression to make the transfer smaller) but it is a working example.

if (e.NativeData != IntPtr.Zero)
{
    Bitmap img = null;
    if (this._commands.CheckForDebug())
    {
        Console.WriteLine("Image data transferred.");
    }
    //Need to save out the data.
    img = e.NativeData.GetDrawingBitmap();

    if (img != null)
    {
         string fileName = "RandomFileName.";

         string fileType = this._commands.GetFileType();

         switch (fileType)
         {
             case "png":
                fileName += "png";
                ImageExtensions.SavePNG(img, fileName, 50L);
                break;
             case "jpeg":
                fileName += "jpeg";
                ImageExtensions.SaveJPEG(img, fileName, 50L);
                break;
             default:
                fileName += "png";
                ImageExtensions.SavePNG(img, fileName, 50L);
                break;
          }
    }
}

public static void SaveJPEG(Image img, string filePath, long quality)
    {
        var encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,   quality);
        img.Save(filePath, GetEncoder(ImageFormat.Jpeg), encoderParameters);
    }

Upvotes: 2

Related Questions