Home > Back-end >  Combining 2 images does not what I expect
Combining 2 images does not what I expect

Time:06-21

I am trying to scan images using twaindotnet, and as long as the user keeps scanning I want to add the scanned image to the already scanned image.

In other words, when the user does his first scan, he well see the scan appear in an PictureBox, and when he performs his second scan, he will see in the PictureBox the first scan and below that the second scan.
After the third scan he will see in the PictureBox the first scan, below that the second scan and below that the third scan.
And so on...

So in the PictureBox there should actual be one large image, that has the combined height of all scans.

So I tried this

        private void buttonScan_Click(object sender, EventArgs e)
        {
            _twain = new Twain(new WinFormsWindowMessageHook(this));

            _twain.ScanningComplete  = _twain_ScanningComplete;
            _twain.TransferImage  = _twain_TransferImage;
            _twain.SelectSource(_twain.SourceNames[0]);
            ScanSettings scanSettings = new ScanSettings();

            /// to do: figure out how to use scansettings
            //scanSettings.Page.Size = TwainDotNet.TwainNative.PageType.A4;
            //scanSettings.Resolution.Dpi = 800;

            _twain.StartScanning(scanSettings);
        }

        private void _twain_ScanningComplete(object sender, ScanningCompleteEventArgs e)
        {
            buttonNextStep.Enabled = true;

            _twain.ScanningComplete -= _twain_ScanningComplete;
            _twain.TransferImage -= _twain_TransferImage;
        }


        private void _twain_TransferImage(object sender, TransferImageEventArgs e)
        {
            if (e.Image != null)
            {
                if (pictureBox1.Image == null)
                {
                    pictureBox1.Image = e.Image;
                }
                else
                {
                    Bitmap bitmap = new Bitmap(pictureBox1.Image.Width, pictureBox1.Image.Height   e.Image.Height);
                    using (Graphics g = Graphics.FromImage(bitmap))
                    {
                        g.DrawImage(pictureBox1.Image, 0, 0);
                        g.DrawImage(e.Image, 0, pictureBox1.Image.Height);

                        pictureBox1.Image = bitmap;
                    }
                }
            }
        }

which I based on this enter image description here

CodePudding user response:

Try forcing images .Width and .Height in g.DrawImage:

g.DrawImage(pictureBox1.Image, 0, 0, pictureBox1.Image.Width, pictureBox1.Image.Height);
g.DrawImage(e.Image, 0, pictureBox1.Image.Height, e.Image.Width, e.Image.Height);

Here is an explanation of this behavior: https://stackoverflow.com/a/47695040/2400834

  • Related