Convertir página web a imagen de ASP.NET


Me gustaría crear una función en C# que tome una página web específica y la cubra con una imagen JPG desde dentro ASP.NET. No quiero hacer esto a través de un tercero o servicio de miniaturas, ya que necesito la imagen completa. Asumo que tendría que aprovechar de alguna manera el control del navegador web desde dentro ASP.NET pero no puedo ver por dónde empezar. ¿Alguien tiene ejemplos?

Author: Keith Adler, 2010-04-26

6 answers

Ok, esto fue bastante fácil cuando combiné varias soluciones diferentes:

Estas soluciones me dieron una forma segura de usar el navegador web desde ASP.NET:

Http://www.beansoftware.com/ASP.NET-Tutorials/Get-Web-Site-Thumbnail-Image.aspx

Http://www.eggheadcafe.com/tutorials/aspnet/b7cce396-e2b3-42d7-9571-cdc4eb38f3c1/build-a-selfcaching-asp.aspx

Esta solución me dio una manera de convertir BMP a JPG:

Bmp a jpg / png en C #

Simplemente adapté el código y puse lo siguiente en a .cs:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;

public class WebsiteToImage
{
    private Bitmap m_Bitmap;
    private string m_Url;
    private string m_FileName = string.Empty;

    public WebsiteToImage(string url)
    {
        // Without file 
        m_Url = url;
    }

    public WebsiteToImage(string url, string fileName)
    {
        // With file 
        m_Url = url;
        m_FileName = fileName;
    }

    public Bitmap Generate()
    {
        // Thread 
        var m_thread = new Thread(_Generate);
        m_thread.SetApartmentState(ApartmentState.STA);
        m_thread.Start();
        m_thread.Join();
        return m_Bitmap;
    }

    private void _Generate()
    {
        var browser = new WebBrowser { ScrollBarsEnabled = false };
        browser.Navigate(m_Url);
        browser.DocumentCompleted += WebBrowser_DocumentCompleted;

        while (browser.ReadyState != WebBrowserReadyState.Complete)
        {
            Application.DoEvents();
        }

        browser.Dispose();
    }

    private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        // Capture 
        var browser = (WebBrowser)sender;
        browser.ClientSize = new Size(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
        browser.ScrollBarsEnabled = false;
        m_Bitmap = new Bitmap(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
        browser.BringToFront();
        browser.DrawToBitmap(m_Bitmap, browser.Bounds);

        // Save as file? 
        if (m_FileName.Length > 0)
        {
            // Save 
            m_Bitmap.SaveJPG100(m_FileName);
        }
    }
}

public static class BitmapExtensions
{
    public static void SaveJPG100(this Bitmap bmp, string filename)
    {
        var encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
        bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters);
    }

    public static void SaveJPG100(this Bitmap bmp, Stream stream)
    {
        var encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
        bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);
    }

    public static ImageCodecInfo GetEncoder(ImageFormat format)
    {
        var codecs = ImageCodecInfo.GetImageDecoders();

        foreach (var codec in codecs)
        {
            if (codec.FormatID == format.Guid)
            {
                return codec;
            }
        }

        // Return 
        return null;
    }
}

Y puede llamarlo de la siguiente manera:

WebsiteToImage websiteToImage = new WebsiteToImage( "http://www.cnn.com", @"C:\Some Folder\Test.jpg");
websiteToImage.Generate();

Funciona tanto con un archivo como con una secuencia. Asegúrese de agregar una referencia al Sistema.Windows.Formularios a su ASP.NET proyecto. espero que esto ayude.

ACTUALIZAR: He actualizado el código para incluir la capacidad de capturar la página completa y no requerir ninguna configuración especial para capturar solo una parte de ella.

 43
Author: Keith Adler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:17

Aquí está mi implementación usando métodos de extensión y task factory en lugar de thread:

/// <summary>
    /// Convert url to bitmap byte array
    /// </summary>
    /// <param name="url">Url to browse</param>
    /// <param name="width">width of page (if page contains frame, you need to pass this params)</param>
    /// <param name="height">heigth of page (if page contains frame, you need to pass this params)</param>
    /// <param name="htmlToManipulate">function to manipulate dom</param>
    /// <param name="timeout">in milliseconds, how long can you wait for page response?</param>
    /// <returns>bitmap byte[]</returns>
    /// <example>
    /// byte[] img = new Uri("http://www.uol.com.br").ToImage();
    /// </example>
    public static byte[] ToImage(this Uri url, int? width = null, int? height = null, Action<HtmlDocument> htmlToManipulate = null, int timeout = -1)
    {
        byte[] toReturn = null;

        Task tsk = Task.Factory.StartNew(() =>
        {
            WebBrowser browser = new WebBrowser() { ScrollBarsEnabled = false };
            browser.Navigate(url);

            browser.DocumentCompleted += (s, e) =>
            {
                var browserSender = (WebBrowser)s;

                if (browserSender.ReadyState == WebBrowserReadyState.Complete)
                {
                    if (htmlToManipulate != null) htmlToManipulate(browserSender.Document);

                    browserSender.ClientSize = new Size(width ?? browser.Document.Body.ScrollRectangle.Width, height ?? browser.Document.Body.ScrollRectangle.Bottom);
                    browserSender.ScrollBarsEnabled = false;
                    browserSender.BringToFront();

                    using (Bitmap bmp = new Bitmap(browserSender.Document.Body.ScrollRectangle.Width, browserSender.Document.Body.ScrollRectangle.Bottom))
                    {
                        browserSender.DrawToBitmap(bmp, browserSender.Bounds);
                        toReturn = (byte[])new ImageConverter().ConvertTo(bmp, typeof(byte[]));
                    }
                }

            };

            while (browser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }

            browser.Dispose();

        }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

        tsk.Wait(timeout);

        return toReturn;
    }
 2
Author: Alexandre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-28 21:00:41

Buena solución por el Sr. Cat Man Do.

He necesitado agregar una fila para suprimir algunos errores que surgieron en algunas páginas web (con la ayuda de un impresionante colega mío)

private void _Generate()
{
    var browser = new WebBrowser { ScrollBarsEnabled = false };

    browser.ScriptErrorsSuppressed = true;        //           <--

    browser.Navigate(m_Url);
    browser.DocumentCompleted += WebBrowser_DocumentCompleted;
}

...

Gracias Señor Do

 2
Author: Fourier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-09 13:13:02

Hay un buen artículo de Peter Bromberg sobre este tema aquí. Su solución parece hacer lo que necesitas...

 1
Author: Dean Kuga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-26 17:40:00

Puede usar WatiN para abrir un nuevo navegador, luego capturar la pantalla y recortarla apropiadamente.

 0
Author: Ian P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-30 06:36:05

La solución es perfecta, solo necesita una fijación en la línea que establece el ANCHO de la imagen. Para páginas con UNA ALTURA GRANDE, no establece el ANCHO apropiadamente:

    //browser.ClientSize = new Size(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom);
    browser.ClientSize = new Size(1000, browser.Document.Body.ScrollRectangle.Bottom);

Y para añadir una referencia al Sistema.Windows.Formularios, debe hacerlo en. NET-tab de AGREGAR REFERENCIA en lugar de COM-tab.

 0
Author: Kardo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-07 05:11:48