C# winform cefsharp 截取网页元素图片
- 通过元素id找到该元素在网页中的坐标
- 获取winform窗体的坐标位置
- 计算该元素对应的在桌面上坐标
- 根据截图接口传入该元素对应桌面坐标,截取该元素图片
效果图如下:
调用代码如下,主要两个函数:
public string GetPicPath()
{
try
{
string script =
@"
(function(){
var img = document.getElementById('verifyImg');
var result=false;
if(img!=null){
oRect = img.getBoundingClientRect();
result = oRect.left+','+oRect.top+','+oRect.right+','+oRect.bottom;
return result;
}
return result;
})();
";
Task<JavascriptResponse> jr = browser.EvaluateScriptAsync(script);
jr.Wait();//等待脚本执行完
if (jr != null)
{
var response = jr.Result;
Log.println("d", response.Success + "");
if (response.Success && response.Result != null)
{
Log.println("d","ok"+","+ response.Result);
string xywh = response.Result.ToString();
Log.println("d", "xywh=" + xywh);
if (xywh.Contains(","))
{
string[] s = xywh.Split(',');
int x = Convert.ToInt32(s[0]);
int y = Convert.ToInt32(s[1]);
int w = Convert.ToInt32(s[2])- Convert.ToInt32( s[0]);
int h = Convert.ToInt32(s[3])- Convert.ToInt32(s[1]);
Log.println("d", "x="+x+",y=" + y+",w="+w+",h="+h);
//标题高度
int title_h = this.Height - this.ClientRectangle.Height;
//对应的窗体左边框距离浏览器控件宽度是18,标题和浏览器控件间隙高度也是18
string imgPath = screenCut(this.Location.X+x+18, this.Location.Y+y+ title_h + 18, w, h);
Log.println("d","图片路径:"+imgPath);
this.pictureBox1.Image = Image.FromFile(imgPath);
return imgPath;
}
}
}
} catch (Exception) { }
return "";
}
public string screenCut(int x,int y, int width, int height)
{
try
{
//屏幕宽
//int iWidth = Screen.PrimaryScreen.Bounds.Width;
//屏幕高
//int iHeight = Screen.PrimaryScreen.Bounds.Height;
//按照屏幕宽高创建位图
Image img = new Bitmap(width, height);
//从一个继承自Image类的对象中创建Graphics对象
Graphics gc = Graphics.FromImage(img);
//抓屏并拷贝到myimage里
gc.CopyFromScreen(new Point(x, y), new Point(0, 0), new Size(width, height));
//this.BackgroundImage = img;
//保存位图
string filePath = @"img/" + Guid.NewGuid().ToString() + ".jpg";
img.Save(filePath);
Log.println("d", "截图完成!"+ this.Location.X+","+ this.Location.Y+","+ width+","+ height);
return filePath;
} catch (Exception) { }
return "";
}
总结:之前尝试过其他的方法,发现截出来图是空白的,这个方法有个缺点,就是要截取的图片不能被挡住,因为这个是调用电脑屏幕截图的