Search code examples
c#internet-explorerseleniumscreenshotaforge

Screen capture by selenium C#, Internet Explorer vs. Chrome to use by aForge,


public static void ScreenShotAndSave(driver, string FileName)
{
        string userPath = "thePath//image.bmp"
        Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
        ss.SaveAsFile(userPath, ImageFormat.Bmp);
}

I use the above code to capture the screenshot in any browsers. And I use the captured image as a source. I have a saved template image in bmp Format24bppRgb. As you will notice, aForge only compare 24 or 8 bpp images. However, when running the test by IE the file get saved in Format32bppArgb, and it cannot be used at aForge. I would be happy to hear your suggestions regarding my issue. Please feel free to ask me further questions. Thanks in advance.


Solution

  • I use this function to remove the alpha channel with Selenium:

    public static Bitmap RemoveAlphaChannel(Bitmap bitmapSrc) {
        Rectangle rect = new Rectangle(0, 0, bitmapSrc.Width, bitmapSrc.Height);
        Bitmap bitmapDest = (Bitmap)new Bitmap(bitmapSrc.Width, bitmapSrc.Height, PixelFormat.Format24bppRgb);
        BitmapData dataSrc = bitmapSrc.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
        BitmapData dataDest = bitmapDest.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
        NativeMethods.CopyMemory(dataDest.Scan0, dataSrc.Scan0, (uint)dataSrc.Stride * (uint)dataSrc.Height);
        bitmapSrc.UnlockBits(dataSrc);
        bitmapDest.UnlockBits(dataDest);
        return bitmapDest;
    }
    
    static class NativeMethods {
    
        const string KERNEL32 = "Kernel32.dll";
    
        [DllImport(KERNEL32)]
        public extern static void CopyMemory(IntPtr dest, IntPtr src, uint length);
    
    }
    

    This is a usage example with Selenium:

    var screenshot = driver.GetScreenshot();
    using(var img = (Bitmap)Bitmap.FromStream(new MemoryStream(screenshot.AsByteArray), false, false)){
        RemoveAlphaChannel(img).Save("abcd.png", ImageFormat.Png);
    }