Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a bitmap of the WatiN image element?

Tags:

c#

.net

watin

I have some textfields processed and other elements, but I want to get the bitmap so I can save it somewhere on disk. I need to do it directly from WatiN if this is possible.

How can I do this?

like image 375
Daniel G Avatar asked Jan 07 '11 15:01

Daniel G


1 Answers

I had a similar problem some time ago. Watin can't do this directly but it exposes the mshtml objects needed to get some results.

At the time my code was pretty much like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WatiN.Core;
using WatiN.Core.Native.InternetExplorer;
using mshtml;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Browser browser = new IE("http://www.google.com");
            IEElement banner = browser.Images[0].NativeElement as IEElement;

            IHTMLElement bannerHtmlElem = banner.AsHtmlElement;
            IEElement bodyNative = browser.Body.NativeElement as IEElement;
            mshtml.IHTMLElement2 bodyHtmlElem = (mshtml.IHTMLElement2)bodyNative.AsHtmlElement;
            mshtml.IHTMLControlRange controlRange = (mshtml.IHTMLControlRange)bodyHtmlElem.createControlRange();

            controlRange.add((mshtml.IHTMLControlElement)bannerHtmlElem);
            controlRange.execCommand("Copy", false, System.Reflection.Missing.Value);
            controlRange.remove(0);

            if (Clipboard.GetDataObject() != null)
            {
                IDataObject data = Clipboard.GetDataObject();
                if (data.GetDataPresent(DataFormats.Bitmap))
                {
                    System.Drawing.Image image = (System.Drawing.Image)data.GetData(DataFormats.Bitmap, true);
                    // do something here
                }
            }
        }

    }
}

This little hack, basically, tries to copy the image to the clipboard. However I had a couple of problems making it work properly and ended up snapshoting the region around the image and saving it to disk.

Although this may not be very helpful it may point you in some directions..

like image 134
Bruno Avatar answered Sep 30 '22 08:09

Bruno