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

前端 未结 5 2114
暗喜
暗喜 2020-12-17 01:27

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

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-17 02:10

    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 += \"\";");
    ie.RunScript("document.body.innerHTML += \"\";");
    

    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/(?.+?),(?.+)").Groups["data"].Value;
                    var binData = Convert.FromBase64String(base64Data);
                    Bitmap im;
                    using (var stream = new MemoryStream(binData))
                    {
                        im = new Bitmap(stream);
                    }
    

    Hope it helps :)

提交回复
热议问题