twain / twain-cs

A C# interface for TWAIN
172 stars 67 forks source link

TWAIN.cs Native Transfer Memory Cloning Not Necessary? #34

Open mattzirkle opened 5 years ago

mattzirkle commented 5 years ago

If you look at the function TWAIN::NativeToBitmap, you will find the following code:

// So we make a copy (ick)...
Bitmap bitmap;
switch (bitmapinfoheader.biBitCount)
{
    default:
    case 24:
        bitmap = bitmapStream.Clone(new Rectangle(0, 0, bitmapStream.Width, bitmapStream.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
        break;
    case 8:
        bitmap = bitmapStream.Clone(new Rectangle(0, 0, bitmapStream.Width, bitmapStream.Height), System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
        break;
    case 1:
        bitmap = bitmapStream.Clone(new Rectangle(0, 0, bitmapStream.Width, bitmapStream.Height), System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
        break;
}

// Fix the resolution...
bitmap.SetResolution((int)(bitmap.HorizontalResolution + 0.5), (int)(bitmap.VerticalResolution + 0.5));

As you can tell by the comments, it looks like the intention here is to make sure the Bitmap has the correct PixelFormat. However, from my testing, it looks like the Bitmap in the variable bitmapStream that is created from the byte[] already has the correct PixelFormat for what was selected (full color [PixelFormat.Format24bppRgb], grayscale [PixelFormat.Format8bppIndexed], or black and white [PixelFormat.Format1bppIndexed]).

Is there a reason that the PixelFormat would come back incorrect that the copy is necessary? Or is this a relic of something that was not handled in C++ but is handled in the .NET Framework (GDI+)?

mattzirkle commented 5 years ago

Also, right now this is tied directly to returning a Bitmap object. Something that would be more performant is to return a MemoryStream. A MemoryStream is already getting created in this case, so it might not be too much work to change all of the transfer methods to use this as well.