如何获取 WatiN 图像元素的位图?

发布于 2024-10-11 01:43:12 字数 89 浏览 6 评论 0原文

我处理了一些文本字段和其他元素,但我想获取位图,以便可以将其保存在磁盘上的某个位置。如果可能的话,我需要直接从 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一向肩并 2024-10-18 01:43:12

前段时间我也遇到过类似的问题。
Watin 无法直接执行此操作,但它公开了获取某些结果所需的 mshtml 对象。

当时我的代码几乎是这样的:

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
                }
            }
        }

    }
}

这个小技巧基本上是尝试将图像复制到剪贴板。然而,我在使其正常工作时遇到了一些问题,最终对图像周围的区域进行了快照并将其保存到磁盘。

虽然这可能不是很有帮助,但它可能会为您指明一些方向。

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..

枯寂 2024-10-18 01:43:12

我认为你不能直接从 WatiN 获取二进制信息。但是,您可以使用 Image.Uri 方法为您提供图像的 URI。这样就可以很容易地通过http请求下载它了。

using (Browser browser = new IE("http://www.sp4ce.net/computer/2011/01/06/how-to-use-WatiN-with-NUnit.en.html"))
{
   Image image = browser.Images[0];
   Console.Write(image.Uri);

   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(image.Uri);
   WebResponse response = request.GetResponse();
   using (Stream stream = response.GetResponseStream())
   using (FileStream fs = File.OpenWrite(@"c:\foo.png"))
   {
      byte[] bytes = new byte[1024];
      int count;
      while((count = stream.Read(bytes, 0, bytes.Length))!=0)
      {
         fs.Write(bytes, 0, count);
      }
   }
}

希望这有帮助

I don't think you can get the binary information directly from WatiN. However you have Image.Uri method give you the URI of the image. So then it is easy to download it wih http request.

using (Browser browser = new IE("http://www.sp4ce.net/computer/2011/01/06/how-to-use-WatiN-with-NUnit.en.html"))
{
   Image image = browser.Images[0];
   Console.Write(image.Uri);

   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(image.Uri);
   WebResponse response = request.GetResponse();
   using (Stream stream = response.GetResponseStream())
   using (FileStream fs = File.OpenWrite(@"c:\foo.png"))
   {
      byte[] bytes = new byte[1024];
      int count;
      while((count = stream.Read(bytes, 0, bytes.Length))!=0)
      {
         fs.Write(bytes, 0, count);
      }
   }
}

Hope this helps

七七 2024-10-18 01:43:12

不久前,我也需要提取图像数据,所以我提出了这个解决方案:

在页面内创建一个隐藏字段和

ie.RunScript("document.body.innerHTML += \"<input type='hidden' id='hidden64'/>\";");
ie.RunScript("document.body.innerHTML += \"<canvas id='canv' width='150px' height='40px' ></canvas>\";");

使用javascript将其转换为base64并检索其值,

ie.RunScript("var c = document.getElementById('canv');");
ie.RunScript("var ctx = c.getContext('2d');");
ie.RunScript("var img = document.getElementsByName('imgCaptcha')[0];");
ie.RunScript("ctx.drawImage(img, 10, 10);");
ie.RunScript("document.getElementById('hidden64').value=c.toDataURL();");

然后检索编码值,

string data = ie.Element(Find.ById("hidden64")).GetAttributeValue("value");

var base64Data = Regex.Match(data, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
                var binData = Convert.FromBase64String(base64Data);
                Bitmap im;
                using (var stream = new MemoryStream(binData))
                {
                    im = new Bitmap(stream);
                }

画布希望它有所帮助:)

A while ago I needed to extract image data too so I came with this solution:

Create an hidden field and a canvas inside the page using

ie.RunScript("document.body.innerHTML += \"<input type='hidden' id='hidden64'/>\";");
ie.RunScript("document.body.innerHTML += \"<canvas id='canv' width='150px' height='40px' ></canvas>\";");

transform it to base64 using javascript and retrieving its value

ie.RunScript("var c = document.getElementById('canv');");
ie.RunScript("var ctx = c.getContext('2d');");
ie.RunScript("var img = document.getElementsByName('imgCaptcha')[0];");
ie.RunScript("ctx.drawImage(img, 10, 10);");
ie.RunScript("document.getElementById('hidden64').value=c.toDataURL();");

then retrieving the codified value

string data = ie.Element(Find.ById("hidden64")).GetAttributeValue("value");

var base64Data = Regex.Match(data, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
                var binData = Convert.FromBase64String(base64Data);
                Bitmap im;
                using (var stream = new MemoryStream(binData))
                {
                    im = new Bitmap(stream);
                }

Hope it helps :)

电影里的梦 2024-10-18 01:43:12
public Image GetImageFromElement(IHTMLElement Element)
    {
        int width = (int)Element.style.width;
        int height = (int)Element.style.height;
        IHTMLElementRender2 render = (IHTMLElementRender2)Element;

        Bitmap screenCapture = new Bitmap(width, height);
        Rectangle drawRectangle = new Rectangle(0, 0, width, height);
        this.DrawToBitmap(screenCapture, drawRectangle);
        Graphics graphics = Graphics.FromImage(screenCapture);

        IntPtr graphicshdc = graphics.GetHdc();
        render.DrawToDC(graphicshdc);
        graphics.ReleaseHdc(graphicshdc);
        graphics.Dispose();

        return screenCapture as Image;
    }

这就是我用于 php 生成图像的方法。
它在我自己的 WebBrowserClass 中实现,它扩展了网络浏览器控件。

(所以“this”= WebBrowser)

但是我们必须导入 IHTMLElementRender2 接口才能使用该方法。

[Guid("3050f669-98b5-11cf-bb82-00aa00bdce0b"),
         InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
         ComVisible(true),
         ComImport]
    interface IHTMLElementRender2
    {
        void DrawToDC([In] IntPtr hDC);
        void SetDocumentPrinter([In, MarshalAs(UnmanagedType.BStr)] string bstrPrinterName, [In] IntPtr hDC);
    };

我大约一年前在网上发现了这个方法,所以如果你搜索它,你可能会找到更多信息。

伊万

public Image GetImageFromElement(IHTMLElement Element)
    {
        int width = (int)Element.style.width;
        int height = (int)Element.style.height;
        IHTMLElementRender2 render = (IHTMLElementRender2)Element;

        Bitmap screenCapture = new Bitmap(width, height);
        Rectangle drawRectangle = new Rectangle(0, 0, width, height);
        this.DrawToBitmap(screenCapture, drawRectangle);
        Graphics graphics = Graphics.FromImage(screenCapture);

        IntPtr graphicshdc = graphics.GetHdc();
        render.DrawToDC(graphicshdc);
        graphics.ReleaseHdc(graphicshdc);
        graphics.Dispose();

        return screenCapture as Image;
    }

That's the Method i use for php generated images.
It's implimented in my own WebBrowserClass, which extends the webbrowser control.

(so "this" = WebBrowser)

But we have to import the IHTMLElementRender2 interface, to use the method.

[Guid("3050f669-98b5-11cf-bb82-00aa00bdce0b"),
         InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
         ComVisible(true),
         ComImport]
    interface IHTMLElementRender2
    {
        void DrawToDC([In] IntPtr hDC);
        void SetDocumentPrinter([In, MarshalAs(UnmanagedType.BStr)] string bstrPrinterName, [In] IntPtr hDC);
    };

I found this method in web, about 1 year ago, so if you search for it you might find more information.

Iwan

青柠芒果 2024-10-18 01:43:12

我有这样的问题,我无法解决。 PHP 一直生成新图像,因此我使用了 CaptureWebPageToFile() 方法。

I had such problem, and I could not solve it. PHP generated new images all the time so I used the CaptureWebPageToFile() method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文