twain-cs icon indicating copy to clipboard operation
twain-cs copied to clipboard

TWAIN.cs Native Transfer Memory Cloning Not Necessary?

Open mattzirkle opened this issue 5 years ago • 1 comments

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 avatar Jun 03 '19 19:06 mattzirkle

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.

mattzirkle avatar Jun 03 '19 19:06 mattzirkle