zoukankan      html  css  js  c++  java
  • 在web项目中使用WebBrowser类给网站抓图

    最近做一个WEB项目,其中要求有个功能就是程序能网页抓图,举个例子:
    在test.aspx页面上放一个TextBox和一个Button,TextBox用来输入要抓取的网页地址,然后按了Button之后,服务器要对前面输入的网址进行抓图,然后显示出来。我把抓图的业务逻辑做成一个类:

    using System;
    using System.Data;
    using System.Windows.Forms;
    using System.Drawing;

    /// <summary>
    /// WebSnap :网页抓图对象
    /// </summary>
    public class WebSnap2
    {

    public WebSnap2()
    {
    //
    // TODO: 在此处添加构造函数逻辑
    //
    }

    /// <summary>
    /// 开始一个抓图并返回图象
    /// </summary>
    /// <param name="Url">要抓取的网页地址</param>
    /// <returns></returns>
    public Bitmap StartSnap(string Url)
    {
    WebBrowser myWB = this.GetPage(Url);
    Bitmap returnValue = this.SnapWeb(myWB);
    myWB.Dispose();
    return returnValue;
    }

    private WebBrowser GetPage(string Url)
    {
    WebBrowser myWB = new WebBrowser();
    myWB.ScrollBarsEnabled = false;
    myWB.Navigate(Url);
    while (myWB.ReadyState != WebBrowserReadyState.Complete)
    {
    System.Windows.Forms.Application.DoEvents();
    }
    return myWB;
    }

    private Bitmap SnapWeb(WebBrowser wb)
    {
    HtmlDocument hd = wb.Document;
    int height = Convert.ToInt32(hd.Body.GetAttribute("scrollHeight")) + 10;
    int width = Convert.ToInt32(hd.Body.GetAttribute("scrollWidth")) + 10;
    wb.Height = height;
    wb.Width = width;
    Bitmap bmp = new Bitmap(width, height);
    Rectangle rec = new Rectangle();
    rec.Width = width;
    rec.Height = height;
    wb.DrawToBitmap(bmp, rec);
    return bmp;
    }

    }

    然后在test.asp的button_click事件里面调用:

            WebSnap ws = new WebSnap();
    Bitmap bmp= ws.StartSnap(TextBox1.Text);
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    Response.BinaryWrite(ms.GetBuffer());



    作者:BuildNewApp
    出处:http://syxchina.cnblogs.comBuildNewApp.com
    本文版权归作者、博客园和百度空间共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则作者会诅咒你的。
    如果您阅读了我的文章并觉得有价值请点击此处,谢谢您的肯定1。
  • 相关阅读:
    第七周作业
    第六周作业
    第五周作业
    第四周作业
    第三周作业
    第二周作业
    第一周作业
    训练神经网络的一些经验分享
    Latex 安装 教程
    关于python环境的一切注意事项
  • 原文地址:https://www.cnblogs.com/syxchina/p/2197315.html
Copyright © 2011-2022 走看看