简体   繁体   English

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

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

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. 如果可能的话,我需要直接从WatiN进行。

How can I do this? 我怎样才能做到这一点?

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. Watin无法直接执行此操作,但它会公开获取某些结果所需的mshtml对象。

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.. 虽然这可能不是很有帮助,但它可能会指向某些方向..

I don't think you can get the binary information directly from WatiN. 我认为你不能直接从WatiN获取二进制信息。 However you have Image.Uri method give you the URI of the image. 但是你有Image.Uri方法给你图像的URI。 So then it is easy to download it wih http request. 因此,很容易下载它与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);
      }
   }
}

Hope this helps 希望这可以帮助

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 使用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();");

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 :) 希望能帮助到你 :)

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. 这就是我用于php生成的图像的方法。 It's implimented in my own WebBrowserClass, which extends the webbrowser control. 它在我自己的WebBrowserClass中得到了肯定,它扩展了webbrowser控件。

(so "this" = WebBrowser) (所以“this”= WebBrowser)

But we have to import the IHTMLElementRender2 interface, to use the method. 但我们必须导入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);
    };

I found this method in web, about 1 year ago, so if you search for it you might find more information. 我在大约1年前在网上找到了这种方法,所以如果你搜索它,你可能会找到更多的信息。

Iwan 我要

I had such problem, and I could not solve it. 我有这样的问题,我无法解决它。 PHP generated new images all the time so I used the CaptureWebPageToFile() method. PHP始终生成新图像,因此我使用了CaptureWebPageToFile()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM