如何将网页保存为图像

发布于 2024-07-16 07:37:06 字数 165 浏览 13 评论 0原文

我有一个 WebBrowser 控件,我想将查看的整个页面保存到图像(任何网页)。 我尝试使用 IHTMLElementRender 接口,但它不适用于所有网页。 也许我做错了什么,因为有时快照包含滚动条,有时只是部分的。 您是否有一个可以将整个网页保存为图像的工作示例?

谢谢。

I have a WebBrowser control and I want to save the whole page viewed to image (any web page).
I tried using IHTMLElementRender interface but it didn't work for all web pages. Maybe I'm doing something wrong because sometimes the snapshot included the scrollers and sometimes it was just partial.
Do you have a working example that can save the whole web page to an image?

Thanks.

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

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

发布评论

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

评论(3

獨角戲 2024-07-23 07:37:06

有一篇 很棒的 CodeProject 文章,展示了如何使用 IE 完成此任务引擎。 如果您更喜欢使用其他浏览器的渲染引擎,那么这是一个开始学习的好地方。 还有一个用于 Firefox 的 一个插件 可以做到这一点,你可以深入研究它的内部结构,深入了解如何在 Firefox 中实现这一目标。

There is a great CodeProject article that shows hows to accomplish this task using the IE engine. If you prefer to use another browser's rendering engine, this is a good place to start learning. There is also an addon for Firefox which will do this, you could dig into the internals of it to get insight on how to accomplish this in firefox.

海夕 2024-07-23 07:37:06

您可以使用这些人 http://webthumb.bluga.net/home 和以下代码。 如果您每月只需要生成一些图像,那么它是免费的,但更多图像会收取一点费用。

(我与他们没有任何关系,我过去只是用过这个)

public enum OutputType
    {
        Png,
        Jpg
    }

    public interface IWebThumbAPI
    {
        int Delay { get; set; }
        int Width { get; set; }
        int Height { get; set; }
        OutputType OutputType { get; set; }
        WebThumbAPI Get(string url);
        WebThumbAPI Get(string url, int x, int y, int width, int height);
        System.Drawing.Image SaveSize(WebThumbSize webThumbSize);
    }

    public class WebThumbAPI : IWebThumbAPI
    {
        private readonly string apiKey;
        private IList<WebThumbResponse> webThumbResponse;
        private string jobId;
        private string ApiUrl { get; set; }
        public int Delay { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public OutputType OutputType { get; set; }

        public WebThumbAPI(string apiKey)
            : this(apiKey, "")
        {
        }

        public WebThumbAPI(string apiKey, string jobId)
        {
            this.apiKey = apiKey;
            OutputType = OutputType.Png;
            Width = 1024;
            Height = 768;
            Delay = 5;
            ApiUrl = "http://webthumb.bluga.net/api.php";
            this.jobId = jobId;
        }

        public WebThumbAPI Get(string url)
        {
            return Get(url, 0, 0, 400, 200);
        }

        public WebThumbAPI Get(string url, int x, int y, int width, int height)
        {
            var outputType = OutputType == OutputType.Jpg ? "jpg" : "png";

            var doc = new XDocument(
                new XElement("webthumb",
                            new XElement("apikey", apiKey),
                             new XElement("request",
                                                 new XElement("url", url),
                                                 new XElement("outputType", outputType),
                                                 new XElement("width", Width),
                                                 new XElement("height", Height),
                                                 new XElement("delay", Delay),
                                                 new XElement("excerpt",
                                                     new XElement("x", x),
                                                     new XElement("y", y),
                                                     new XElement("width", width),
                                                     new XElement("height", height)))
                    )
                );

            var request = getRequest(doc.ToString());
            var webResponse = (HttpWebResponse)request.GetResponse();
            if (webResponse.ContentType == "text/xml")
            {
                var stream = webResponse.GetResponseStream();
                var response = XDocument.Load(XmlReader.Create(stream));
                webThumbResponse = (from xml in response.Descendants("job")
                                    select new WebThumbResponse
                                    {
                                        Estimate = (int)xml.Attribute("estimate"),
                                        Time = (DateTime)xml.Attribute("time"),
                                        Url = (string)xml.Attribute("url"),
                                        Cost = (int)xml.Attribute("cost"),
                                        Job = (string)xml.Value
                                    }).ToList();
                stream.Close();
                if (webThumbResponse.Count == 0)
                    jobId = "-1";
                else
                {
                    jobId = webThumbResponse[0].Job;
                    Thread.Sleep(webThumbResponse[0].Estimate * 1000);
                }

            }
            else
            {
                throw new InvalidOperationException("Failed request");
            }
            return this;
        }

        public System.Drawing.Image SaveSize(WebThumbSize webThumbSize)
        {
            if (jobId == "-1")
                return defaultImage(webThumbSize);
            var doc = new XDocument(
                new XElement("webthumb",
                            new XElement("apikey", apiKey),
                             new XElement("fetch",
                                                 new XElement("job", jobId),
                                                 new XElement("size", Enum.GetName(typeof(WebThumbSize), webThumbSize).ToLower())
                                                 )
                    )
                );
            var request = getRequest(doc.ToString());
            var webResponse = (HttpWebResponse)request.GetResponse();
            var stream = webResponse.GetResponseStream();

            Image image = null;
            try
            {
                image = System.Drawing.Image.FromStream(stream);
            }
            catch
            {
                image = defaultImage(webThumbSize);

            }
            return image;
        }

        private Image defaultImage(WebThumbSize webThumbSize)
        {
            var s = getSize(webThumbSize);
            var b = new Bitmap(s.Width, s.Height);
            var im = Image.FromHbitmap(b.GetHbitmap());
            var gr = System.Drawing.Graphics.FromImage(im);
            gr.Clear(Color.White);
            gr.Dispose();
            return im;
        }

        private static System.Drawing.Size getSize(WebThumbSize size)
        {
            switch (size)
            {
                case WebThumbSize.Small:
                    return new Size(80, 60);
                case WebThumbSize.Excerpt:
                    return new Size(400, 200);
                default:
                    return new Size(1, 1);
            }
        }

        private HttpWebRequest getRequest(string xml)
        {
            var request = (HttpWebRequest)WebRequest.Create(ApiUrl);
            request.Method = "POST";
            request.Timeout = 20000;
            request.ContentType = "text/xml";
            request.UserAgent = @"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/418.8 (KHTML, like Gecko) Safari/419.3";
            request.KeepAlive = false;
            request.Pipelined = false;

            Stream newStream = request.GetRequestStream();
            var encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(xml);
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            return request;
        }
    }

    public class WebThumbResponse
    {
        public DateTime Time;
        public string Job;
        public string Url;
        public int Cost;
        public int Estimate { get; set; }
    }

    public enum WebThumbSize
    {
        Small,
        Medium,
        Medium2,
        Large,
        Excerpt
    }

You could use these guys http://webthumb.bluga.net/home and the following code. If you only need a few images generated per month it is free but they charge a little for more.

(I am in no way affiliated with them, I have just used this in the past)

public enum OutputType
    {
        Png,
        Jpg
    }

    public interface IWebThumbAPI
    {
        int Delay { get; set; }
        int Width { get; set; }
        int Height { get; set; }
        OutputType OutputType { get; set; }
        WebThumbAPI Get(string url);
        WebThumbAPI Get(string url, int x, int y, int width, int height);
        System.Drawing.Image SaveSize(WebThumbSize webThumbSize);
    }

    public class WebThumbAPI : IWebThumbAPI
    {
        private readonly string apiKey;
        private IList<WebThumbResponse> webThumbResponse;
        private string jobId;
        private string ApiUrl { get; set; }
        public int Delay { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public OutputType OutputType { get; set; }

        public WebThumbAPI(string apiKey)
            : this(apiKey, "")
        {
        }

        public WebThumbAPI(string apiKey, string jobId)
        {
            this.apiKey = apiKey;
            OutputType = OutputType.Png;
            Width = 1024;
            Height = 768;
            Delay = 5;
            ApiUrl = "http://webthumb.bluga.net/api.php";
            this.jobId = jobId;
        }

        public WebThumbAPI Get(string url)
        {
            return Get(url, 0, 0, 400, 200);
        }

        public WebThumbAPI Get(string url, int x, int y, int width, int height)
        {
            var outputType = OutputType == OutputType.Jpg ? "jpg" : "png";

            var doc = new XDocument(
                new XElement("webthumb",
                            new XElement("apikey", apiKey),
                             new XElement("request",
                                                 new XElement("url", url),
                                                 new XElement("outputType", outputType),
                                                 new XElement("width", Width),
                                                 new XElement("height", Height),
                                                 new XElement("delay", Delay),
                                                 new XElement("excerpt",
                                                     new XElement("x", x),
                                                     new XElement("y", y),
                                                     new XElement("width", width),
                                                     new XElement("height", height)))
                    )
                );

            var request = getRequest(doc.ToString());
            var webResponse = (HttpWebResponse)request.GetResponse();
            if (webResponse.ContentType == "text/xml")
            {
                var stream = webResponse.GetResponseStream();
                var response = XDocument.Load(XmlReader.Create(stream));
                webThumbResponse = (from xml in response.Descendants("job")
                                    select new WebThumbResponse
                                    {
                                        Estimate = (int)xml.Attribute("estimate"),
                                        Time = (DateTime)xml.Attribute("time"),
                                        Url = (string)xml.Attribute("url"),
                                        Cost = (int)xml.Attribute("cost"),
                                        Job = (string)xml.Value
                                    }).ToList();
                stream.Close();
                if (webThumbResponse.Count == 0)
                    jobId = "-1";
                else
                {
                    jobId = webThumbResponse[0].Job;
                    Thread.Sleep(webThumbResponse[0].Estimate * 1000);
                }

            }
            else
            {
                throw new InvalidOperationException("Failed request");
            }
            return this;
        }

        public System.Drawing.Image SaveSize(WebThumbSize webThumbSize)
        {
            if (jobId == "-1")
                return defaultImage(webThumbSize);
            var doc = new XDocument(
                new XElement("webthumb",
                            new XElement("apikey", apiKey),
                             new XElement("fetch",
                                                 new XElement("job", jobId),
                                                 new XElement("size", Enum.GetName(typeof(WebThumbSize), webThumbSize).ToLower())
                                                 )
                    )
                );
            var request = getRequest(doc.ToString());
            var webResponse = (HttpWebResponse)request.GetResponse();
            var stream = webResponse.GetResponseStream();

            Image image = null;
            try
            {
                image = System.Drawing.Image.FromStream(stream);
            }
            catch
            {
                image = defaultImage(webThumbSize);

            }
            return image;
        }

        private Image defaultImage(WebThumbSize webThumbSize)
        {
            var s = getSize(webThumbSize);
            var b = new Bitmap(s.Width, s.Height);
            var im = Image.FromHbitmap(b.GetHbitmap());
            var gr = System.Drawing.Graphics.FromImage(im);
            gr.Clear(Color.White);
            gr.Dispose();
            return im;
        }

        private static System.Drawing.Size getSize(WebThumbSize size)
        {
            switch (size)
            {
                case WebThumbSize.Small:
                    return new Size(80, 60);
                case WebThumbSize.Excerpt:
                    return new Size(400, 200);
                default:
                    return new Size(1, 1);
            }
        }

        private HttpWebRequest getRequest(string xml)
        {
            var request = (HttpWebRequest)WebRequest.Create(ApiUrl);
            request.Method = "POST";
            request.Timeout = 20000;
            request.ContentType = "text/xml";
            request.UserAgent = @"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/418.8 (KHTML, like Gecko) Safari/419.3";
            request.KeepAlive = false;
            request.Pipelined = false;

            Stream newStream = request.GetRequestStream();
            var encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(xml);
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            return request;
        }
    }

    public class WebThumbResponse
    {
        public DateTime Time;
        public string Job;
        public string Url;
        public int Cost;
        public int Estimate { get; set; }
    }

    public enum WebThumbSize
    {
        Small,
        Medium,
        Medium2,
        Large,
        Excerpt
    }
仅此而已 2024-07-23 07:37:06

如果网页大量使用 JS,例如地图应用程序,那么所提供的解决方案将无法很好地工作。

发现此代码与 Webbrowser 控件一起使用更有效,但缺乏更好的...

private void waitTillLoad(WebBrowser webBrowser1)
{
   WebBrowserReadyState loadStatus;

   //wait till beginning of loading next page 
   int waittime = 100000;
   int counter = 0;
   while (true)
   {
       loadStatus = webBrowser1.ReadyState;
       Application.DoEvents();

       if ((counter > waittime) || (loadStatus == WebBrowserReadyState.Uninitialized) || (loadStatus == WebBrowserReadyState.Loading) || (loadStatus == WebBrowserReadyState.Interactive))
       {
           break;
       }
       counter++;
   }

   //wait till the page get loaded.
   counter = 0;
   while (true)
   {
       loadStatus = webBrowser1.ReadyState;
       Application.DoEvents();

       if (loadStatus == WebBrowserReadyState.Complete)
       {
           break;
       }
       counter++;

   }
}

归功于 QualityPoint Technologies,网址为 http://qualitypoint.blogspot.com/2009/03/c-webbrowser-control-synchronization.html

呵呵!

问候,
字节从机

If the webpage is heavy on JS, for instance a maps app the solutions presented won't work very well.

Found this code used with Webbrowser control more efficient, in the lack of better...

private void waitTillLoad(WebBrowser webBrowser1)
{
   WebBrowserReadyState loadStatus;

   //wait till beginning of loading next page 
   int waittime = 100000;
   int counter = 0;
   while (true)
   {
       loadStatus = webBrowser1.ReadyState;
       Application.DoEvents();

       if ((counter > waittime) || (loadStatus == WebBrowserReadyState.Uninitialized) || (loadStatus == WebBrowserReadyState.Loading) || (loadStatus == WebBrowserReadyState.Interactive))
       {
           break;
       }
       counter++;
   }

   //wait till the page get loaded.
   counter = 0;
   while (true)
   {
       loadStatus = webBrowser1.ReadyState;
       Application.DoEvents();

       if (loadStatus == WebBrowserReadyState.Complete)
       {
           break;
       }
       counter++;

   }
}

Credits to QualityPoint Technologies at http://qualitypoint.blogspot.com/2009/03/c-webbrowser-control-synchronization.html

HTH!

Regards,
byte_slave

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