Generate website screenshot/thumbnail with .net webbrowser control on c# asp.net website

by nolovelust 4. December 2010 11:29

Attached code uses altered version of WebPreview from http://smallsharptools.com/Projects/WebPreview/. WebPreview works just fine with most of the sites but, if site you are trying to get screenshot/thumbnail has a JavaScript prompt, by default webbrowser control shows it to user. Its ok if you are using it on an asp.net application, user can click to prompt. Things change if you try to use it on an asp.net website. As there will be no one to click to prompt or even no way to display the prompt code hangs. I have derived from webbrowser control and overwrite OnNavigated event and injected some java script code to disable prompts. Download SmallSharpTools.WebPreview-1.0.0-src.rar (84.13 kb). Keep in mind that webbrowser control uses internet explorer installed on the system and trying to get screenshots/thumbnails of malicious sites may create trouble for your server.
You may also be interested with http://nolovelust.com/post/C-Website-Screenshot-Generator-AKA-Get-Screenshot-of-Webpage-With-Aspnet-C.aspx

 

WebBrowserEx.cs 

 

using System.Windows.Forms;
using mshtml;

namespace SmallSharpTools.WebPreview
{
    class WebBrowserEx : WebBrowser
    {
        public WebBrowserEx() { }

        protected override void OnNavigated(WebBrowserNavigatedEventArgs e)
        {

            HtmlElement he = this.Document.GetElementsByTagName("head")[0];
            HtmlElement se = this.Document.CreateElement("script");
            mshtml.IHTMLScriptElement element = (mshtml.IHTMLScriptElement)se.DomElement;
            string alertBlocker = "window.alert = function () { }";
            element.text = alertBlocker;
            he.AppendChild(se);
            string alertBlockerB = "window.confirm = function () { }";
            element.text = alertBlockerB;
            he.AppendChild(se);
            string alertBlockerC = "window.prompt = function () { }";
            element.text = alertBlockerC;
            he.AppendChild(se);
            string alertBlockerD = "window.open = function () { }";
            element.text = alertBlockerD;
            he.AppendChild(se);
            
            base.OnNavigated(e);
        }
 
    }
}

 

 

 ThumbnailBuilder.cs

 

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

namespace SmallSharpTools.WebPreview
{
    public class ThumbnailBuilder
    {

        #region "  Events  "

        public event EventHandler ExceptionCatching;

        /// 
        /// Raise the ExceptionCatching event
        /// 
        /// 
        protected virtual void OnExceptionCatching(EventArgs e)
        {
            if (ExceptionCatching != null)
            {
                ExceptionCatching(this, e);
            }
        }

        #endregion

        #region "  Methods  "

        public void CreateThumbnail(string sourceFilename, string cachedFilename, int width, int height)
        {
            if (File.Exists(sourceFilename))
            {
                FileInfo inputFile = new FileInfo(sourceFilename);
                FileInfo outputFile = new FileInfo(cachedFilename);

                if (!outputFile.Directory.Exists)
                {
                    outputFile.Directory.Create();
                }

                if (outputFile.Exists && inputFile.CreationTime < outputFile.CreationTime)
                {
                    return;
                }

                try
                {
                    using (Bitmap inBmp = new Bitmap(sourceFilename))
                    {
                        using (Bitmap outBmp = new Bitmap(width, height))
                        {
                            using (Graphics g = Graphics.FromImage(outBmp))
                            {
                                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                g.DrawImage(inBmp, 0, 0, width, height);
                            }
                            outBmp.Save(cachedFilename);
                        }
                        
                    }
                }
                catch (Exception ex)
                {
                    CurrentError = ex;
                    OnExceptionCatching(EventArgs.Empty);
                }
            }
        }

        #endregion

        #region "  Properties  "

        private Exception _currentException = null;

        public Exception CurrentError
        {
            get { return _currentException; }
            set { _currentException = value; }
        }

        #endregion

    }
}

 

SiteConfiguration.cs 

 

using System.Configuration;
using System.Web;

/// 
/// Summary description for SiteConfiguration
/// 
public class SiteConfiguration
{
    
    public static string SourceImageDirectory
    {
        get
        {
            return HttpContext.Current.Server.MapPath(
                ConfigurationManager.AppSettings["SourceImageDirectory"]);
        }
    }

    public static string CachingImageDirectory
    {
        get
        {
            return HttpContext.Current.Server.MapPath(
                ConfigurationManager.AppSettings["CachingImageDirectory"]);
        }
    }

}

 

 

PreviewBuilder.cs 

using System;
using System.ComponentModel;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace SmallSharpTools.WebPreview
{
    public class PreviewBuilder
    {

        #region "  Variables  "

        private string _url = String.Empty;
        private string _filename = String.Empty;

        #endregion
        
        #region "  Constructor  "

        public PreviewBuilder(string url, string filename)
        {
            this._url = url;
            this._filename = filename;
            // Path.Combine(Environment.CurrentDirectory, "output.bmp");
        }

        #endregion

        #region "  Methods  "

        public void CreatePreview()
        {
            ThreadStart ts = new ThreadStart(this.DoWork);
            Thread t = new Thread(ts);
            t.SetApartmentState(ApartmentState.STA);
            t.Start();

            // TODO find the proper way to wait for a thread
            // wait for the thread
            while (t.IsAlive)
            {
                Thread.Sleep(25);
            }
        }

        private void DoWork()
        {
            Bitmap bitmap = GetPreviewImage();

            bitmap.Save(_filename);
            bitmap.Dispose();
        }

        private Bitmap GetPreviewImage()
        {
            WebBrowser wb = new WebBrowserEx();
            wb.ScrollBarsEnabled = false;
            wb.Size = new Size(Width, Height);
            wb.ScriptErrorsSuppressed = true;
            wb.NewWindow += new System.ComponentModel.CancelEventHandler(wb_NewWindow);
            wb.Navigate(_url);

           
            // wait for it to load
            while (wb.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            Bitmap bitmap = new Bitmap(Width, Height);
            Rectangle rect = new Rectangle(0, 0, Width, Height);
            wb.DrawToBitmap(bitmap, rect);
            return bitmap;
        }

        void wb_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        #endregion

        #region "  Properties  "

        private int _width = 1024;

        public int Width
        {
            get { return _width; }
            set { _width = value; }
        }

        private int _height = 768;

        public int Height
        {
            get { return _height; }
            set { _height = value; }
        }

        #endregion

    }
}

 

WebPreviewHandler.ashx 

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Caching;
using SmallSharpTools.WebPreview;

public class WebPreviewHandler : IHttpHandler 
{
    
    public void ProcessRequest (HttpContext context) 
    {
        string url = context.Request.QueryString["url"];
        
        int width;
        if (!int.TryParse(context.Request.QueryString["width"], out width))
        {
            width = 150;
        }
        int height;
        if (!int.TryParse(context.Request.QueryString["height"], out height))
        {
            height = 100;
        }
        
        string sourceFilename = GetSourceFilename(url);
        FileInfo file = new FileInfo(sourceFilename);
        
        if (!file.Exists || file.CreationTime < DateTime.Now.AddHours(-4))
        {
            PreviewBuilder pb = new PreviewBuilder(url, sourceFilename);
            pb.CreatePreview();
        }

        string cachedFilename = GetCachedFilename(sourceFilename, width, height);
        
        if (!File.Exists(cachedFilename))
        {
            ThumbnailBuilder tb = new ThumbnailBuilder();
            // handle the error by throwing it
            tb.ExceptionCatching += delegate { throw tb.CurrentError; };
            tb.CreateThumbnail(sourceFilename, cachedFilename, width, height);
        }  
        
        context.Response.ContentType = GetContentType(cachedFilename);
        context.Response.WriteFile(cachedFilename);
    }
    
    public string GetContentType(string filename)
    {       
        string contentType = "image/x-unknown";
        string ext = Path.GetExtension(filename);
        switch (ext)
        {
            case ".jpg":
                contentType = "image/jpeg";
                break;
            case ".gif":
                contentType = "image/gif";
                break;
            case ".png":
                contentType = "image/png";
                break;
            default:
                contentType = "image/jpeg";
                break;
        }
        return contentType;
    }
    
    public string GetSourceFilename(string url)
    {
        Uri uri = new Uri(url);
        string shortFilename = uri.Host.Replace(".", "_") + 
            uri.LocalPath.Replace("/", "_") + ".png";
        return Path.Combine(SiteConfiguration.SourceImageDirectory, shortFilename);
    }
    
    public string GetCachedFilename(string sourceFilename, int width, int height)
    {
        FileInfo sourceFile = new FileInfo(sourceFilename);
        string shortFilename = sourceFile.Name;
        string ext = Path.GetExtension(shortFilename);
        string replacementEnding = String.Format("-{0}x{1}", width, height) + ext;
        string cachedFilename = shortFilename.Replace(ext, replacementEnding);
        return Path.Combine(SiteConfiguration.CachingImageDirectory, cachedFilename);
    }
    
    public bool IsReusable 
    {
        get {
            return false;
        }
    }

}


Tags: , , , ,

Contribution to C# Website Screenshot Generator AKA Get Screenshot of Webpage With Asp.net C#

by nolovelust 20. May 2010 18:06

Thanks to Colarado State University Web team for their improvments on my C# Website Screenshot Generator AKA Get Screenshot of Webpage With Asp.net C# (see original post first)

With their contribution it now

  • Allowing individuals to pass parameters via querystring.
  • Instead of generic thumbnail sizes of 1, 2, 3 for small, medium, and large, changed to allow individuals to specify the exact thumb size in querystring
  • Ability to now see/download the resulting image in the browser.

 

Updated CutyCaptWrapper.cs:

 

using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;

public class CutyCaptWrapper
{
    /// 
    /// 1 - small
    /// 2 - medium
    /// 3 - large
    /// 
    private int ThumbNailSize { get; set; }
    public bool ThumbKeepAspectRatio { get; set; }
    public int ThumbExpiryTimeInHours { get; set; }
    public string ScreenShotPath { get; set; }
    public string CutyCaptPath { get; set; }
    //public string CutyCaptWorkingDirectory { get; set; }
    public string CutyCaptDefaultArguments { get; set; }
    public int ThumbWidth { get; set; }
    public int ThumbMaxHeight { get; set; }

    public CutyCaptWrapper()
    {
        //default values
        ThumbNailSize = 1;
        ThumbKeepAspectRatio = false;
        ThumbExpiryTimeInHours = 168; //1 week
        ScreenShotPath = HttpContext.Current.Server.MapPath("~/ThumbCache/"); // must be within the web root
        CutyCaptPath = HttpContext.Current.Server.MapPath("~/App_Data/CutyCapt.exe"); // must be within the web root
        //CutyCaptWorkingDirectory = HttpContext.Current.Server.MapPath("~/App_Data/");
        CutyCaptDefaultArguments = " --max-wait=10000 --out-format=jpg --javascript=off --java=off --plugins=off --js-can-open-windows=off --js-can-access-clipboard=off --private-browsing=on";

    }
    /// 
    /// Checks if there is a cached screenshot of the website and returns url path to thumbnail of the website in order to use ase html image element source
    /// Usage example: <img src="<%=CutyCaptWrapper().GetScreenShot("http://google.com")%>" alt="">
    /// 
    public string GetScreenShot(string url)
    {
        if (IsURLValid(url))
        {

            if (!Directory.Exists(ScreenShotPath))
            {
                Directory.CreateDirectory(ScreenShotPath);
            }
            //set thumbnail sizes
            //SetThumbnailSize();
            string ScreenShotFileName = ScreenShotPath + GetScreenShotFileName(url);
            string ScreenShotThumbnailFileName = ScreenShotPath + GetScreenShotThumbnailFileName(ScreenShotFileName, ThumbWidth, ThumbMaxHeight);
            string RunArguments = " --url=" + url + " --out=" + ScreenShotFileName + CutyCaptDefaultArguments;

            FileInfo ScreenShotThumbnailFileNameInfo = new FileInfo(ScreenShotThumbnailFileName);

            if (!ScreenShotThumbnailFileNameInfo.Exists || ScreenShotThumbnailFileNameInfo.CreationTime < DateTime.Now.AddHours(-ThumbExpiryTimeInHours))
            {
          
                    ProcessStartInfo info = new ProcessStartInfo(CutyCaptPath, RunArguments);
                    info.UseShellExecute = false;
                    info.RedirectStandardInput = true;
                    info.RedirectStandardError = true;
                    info.RedirectStandardOutput = true;
                    info.CreateNoWindow = true;
                    //info.WorkingDirectory = CutyCaptWorkingDirectory;
                    using (Process scr = Process.Start(info))
                    {
                        //string output = scr.StandardOutput.ReadToEnd();
                        scr.WaitForExit();
                        ThumbnailCreate(ScreenShotFileName, ScreenShotThumbnailFileName, ThumbWidth, ThumbMaxHeight, ThumbKeepAspectRatio);
                        //delete original file
                        File.Delete(ScreenShotFileName);
                        //return output;
                    }
            }
            return GetRelativeUri(ScreenShotThumbnailFileName);
        }
        else
        {
            return "Wrong URL";
        }
    }
    private void ThumbnailCreate(string sourceFilePath, string outFilePath, int NewWidth, int MaxHeight, bool keepAspectRatio)
    {
        using (Image FullsizeImage = Image.FromFile(sourceFilePath))
        {
            int NewHeight = MaxHeight;
            if (keepAspectRatio)
            {
                NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
                if (NewHeight > MaxHeight)
                {
                    NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
                    NewHeight = MaxHeight;
                }
            }
            using (Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero))
            {
                NewImage.Save(outFilePath, ImageFormat.Png);
            }
        }
    }
    private string GetScreenShotFileName(string url)
    {
        Uri uri = new Uri(url);
        return uri.Host.Replace(".", "_") + uri.LocalPath.Replace("/", "_") + ".png";
    }
    private string GetScreenShotThumbnailFileName(string sourceFilename, int width, int height)
    {
        FileInfo sourceFile = new FileInfo(sourceFilename);
        string shortFilename = sourceFile.Name;
        string ext = Path.GetExtension(shortFilename);
        string replacementEnding = String.Format("{0}x{1}", width, height) + ext;
        return shortFilename.Replace(ext, replacementEnding);
    }
    private string GetRelativeUri(string pathToFile)
    {
        string rootPath = HttpContext.Current.Server.MapPath("~");
        return pathToFile.Replace(rootPath, "").Replace(@"\", "/");
    }
    private bool IsURLValid(string url)
    {
       string strRegex = "^(https?://)"
        + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //user@ 
        + @"(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP- 199.194.52.184 
        + "|" // allows either IP or domain 
        + @"([0-9a-z_!~*'()-]+\.)*" // tertiary domain(s)- www. 
        + @"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // second level domain 
        + "[a-z]{2,6})" // first level domain- .com or .museum 
        + "(:[0-9]{1,4})?" // port number- :80 
        + "((/?)|" // a slash isn't required if there is no file name 
        + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        Regex re = new Regex(strRegex, RegexOptions.Compiled | RegexOptions.IgnoreCase);

        if (re.IsMatch(url))
            return (true);
        else
            return (false);
    }
    private void SmallThumbnail()
    {
        ThumbWidth = 200;
        ThumbMaxHeight = 150;
    }
    private void MediumThumbnail()
    {
        ThumbWidth = 240;
        ThumbMaxHeight = 190;
    }
    private void LargeThumbnail()
    {
        ThumbWidth = 320;
        ThumbMaxHeight = 270;
    }
    private void Res_1024x768()
    {
        ThumbWidth = 1024;
        ThumbMaxHeight = 5000;
    }
    private void Res_1280x1024()
    {
        ThumbWidth = 1280;
        ThumbMaxHeight = 5000;
    }
    private void Res_1920x1200()
    {
        ThumbWidth = 1920;
        ThumbMaxHeight = 5000;
        
    }
    private void SetThumbnailSize()
    {
        if (ThumbNailSize == 1)
        {
            SmallThumbnail();
        }
        if (ThumbNailSize == 2)
        {
            MediumThumbnail();
        }
        if (ThumbNailSize == 3)
        {
            LargeThumbnail();
        }
        if (ThumbNailSize == 1024)
        {
            Res_1024x768();
        }
        if (ThumbNailSize == 1280)
        {
            Res_1280x1024();
        }
        if (ThumbNailSize == 1920)
        {
            Res_1920x1200();
        }
        else
        {
            ThumbNailSize = 1;
        }
    }

}

 

 

Sample usage of updated wrapper 

 

protected void Page_Load(object sender, EventArgs e)
    {
        string url = HttpUtility.HtmlDecode(Request.QueryString["url"]);
        int width;
        int maxheight;
        string result;

        if (int.TryParse(Request.QueryString["width"], out width) == false)
        {
            width = 100;
        }
        if (int.TryParse(Request.QueryString["maxheight"], out maxheight) == false)
        {
            maxheight = 100;
        }

        CutyCaptWrapper ccw = new CutyCaptWrapper();
        ccw.ThumbWidth = width;
        ccw.ThumbMaxHeight = maxheight;
        ccw.ThumbKeepAspectRatio = true;

        if (!string.IsNullOrEmpty(url))
        {
            result = ccw.GetScreenShot(url);
            //System.Threading.Thread.Sleep(5000);
            //Response.Write(result);
            Image1.ImageUrl = Page.ResolveClientUrl("~" + result);
        }
        else
        {
            Response.Write("not a valid url");
        }
        
    }

 

 

 

Tags: , , , ,

Open Source

C# Website Screenshot Generator AKA Get Screenshot of Webpage With Asp.net C#

by nolovelust 25. April 2010 21:45

Before I wrote below C# wrapper I've looked around for a C# code to get screenshot of a web site or url. Although there are many web services provides website screenshot service none of them are free!

I've found http://smallsharptools.com/Projects/WebPreview it works fine and author used windows forms Webbrowser control but there is a problem with it. Webbrowser control uses internet explorer to render pages and if there is any JavaScript prompt on the page you are trying to render it doesn't work. You also have no way of disabling plug-ins and JavaScript. (See http://nolovelust.com/post/Generate-website-screenshotthumbnail-with-net-webbrowser-control-on-c-aspnet-website.aspx for hack to disable JavaScript)

Next candidate was NirSoft's SiteShoter it is nice little application with command line support but it too uses internet explorer to get screenshot of websites.

I finally found CutyCapt, it uses QT Webkit to render web pages and packs everything in to a single file with command line support.

After couple of hours work I ended up a c# wrapper for CutyCapt. Works like a charm Smile.

  • It caches Thumbnails for given hours.
  • It has 3 different thumbnail sizes but you can add as many as you want.
  • It can keep aspect ratio of thumbnails.
  • You can even start your own website screenshot service with it Tongue out

Unlike some paid website screenshot services claim about free website screenshot tools like mine

  • Development & Testing Cost is 0
  • It is not buggy, even if there is a bug it can be fixed as all the code is open source
  • Is not time-consuming and FREE!

To get started download  CutyCapt and my CutyCaptWrapper.zip (4.46 kb), put CutyCapt in to App_Data folder

There is one problem i couldn't fix with this code. If CutyCapt crashes it takes whole site down with it. Having said that, I've been using it on a production site since 2 months and didn't have any problems.

Please see Contribution to C# Website Screenshot Generator AKA Get Screenshot of Webpage With Asp.net C# for updates by Colarado State University Web team

 

Usage

CutyCaptWrapper ccw = new CutyCaptWrapper();
Response.Write(ccw.GetScreenShot("http://bbc.co.uk"));

 Or

<img src="<%=new CutyCaptWrapper().GetScreenShot("http://bbc.co.uk")%>" alt="">

 

 CutyCaptWrapper.cs

using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;

public class CutyCaptWrapper
{
    /// 
    /// 1 - small
    /// 2 - medium
    /// 3 - large
    /// 
    public int ThumbNailSize { get; set; }
    public bool ThumbKeepAspectRatio { get; set; }
    public int ThumbExpiryTimeInHours { get; set; }
    public string ScreenShotPath { get; set; }
    public string CutyCaptPath { get; set; }
    //public string CutyCaptWorkingDirectory { get; set; }
    public string CutyCaptDefaultArguments { get; set; }
    private int ThumbWidth { get; set; }
    private int ThumbHeight { get; set; }

    public CutyCaptWrapper()
    {
        //default values
        ThumbNailSize = 1;
        ThumbKeepAspectRatio = false;
        ThumbExpiryTimeInHours = 168; //1 week
        ScreenShotPath = HttpContext.Current.Server.MapPath("~/ThumbCache/"); // must be within the web root
        CutyCaptPath = HttpContext.Current.Server.MapPath("~/App_Data/CutyCapt.exe"); // must be within the web root
        //CutyCaptWorkingDirectory = HttpContext.Current.Server.MapPath("~/App_Data/");
        CutyCaptDefaultArguments = " --max-wait=10000 --out-format=png --javascript=off --java=off --plugins=off --js-can-open-windows=off --js-can-access-clipboard=off --private-browsing=on";

    }
    /// 
    /// Checks if there is a cached screenshot of the website and returns url path to thumbnail of the website in order to use ase html image element source
    /// Usage example: <img src="<%=CutyCaptWrapper().GetScreenShot("http://google.com")%>" alt="">
    /// 
    public string GetScreenShot(string url)
    {
        if (IsURLValid(url))
        {

            if (!Directory.Exists(ScreenShotPath))
            {
                Directory.CreateDirectory(ScreenShotPath);
            }
            //set thumbnail sizes
            SetThumbnailSize();
            string ScreenShotFileName = ScreenShotPath + GetScreenShotFileName(url);
            string ScreenShotThumbnailFileName = ScreenShotPath + GetScreenShotThumbnailFileName(ScreenShotFileName, ThumbWidth, ThumbHeight);
            string RunArguments = " --url=" + url + " --out=" + ScreenShotFileName + CutyCaptDefaultArguments;

            FileInfo ScreenShotThumbnailFileNameInfo = new FileInfo(ScreenShotThumbnailFileName);

            if (!ScreenShotThumbnailFileNameInfo.Exists || ScreenShotThumbnailFileNameInfo.CreationTime < DateTime.Now.AddHours(-ThumbExpiryTimeInHours))
            {
          
                    ProcessStartInfo info = new ProcessStartInfo(CutyCaptPath, RunArguments);
                    info.UseShellExecute = false;
                    info.RedirectStandardInput = true;
                    info.RedirectStandardError = true;
                    info.RedirectStandardOutput = true;
                    info.CreateNoWindow = true;
                    //info.WorkingDirectory = CutyCaptWorkingDirectory;
                    using (Process scr = Process.Start(info))
                    {
                        //string output = scr.StandardOutput.ReadToEnd();
                        scr.WaitForExit();
                        ThumbnailCreate(ScreenShotFileName, ScreenShotThumbnailFileName, ThumbWidth, ThumbHeight, ThumbKeepAspectRatio);
                        //delete original file
                        File.Delete(ScreenShotFileName);
                        //return output;
                    }
            }
            return GetRelativeUri(ScreenShotThumbnailFileName);
        }
        else
        {
            return "Wrong URL";
        }
    }
    private void ThumbnailCreate(string sourceFilePath, string outFilePath, int NewWidth, int MaxHeight, bool keepAspectRatio)
    {
        using (Image FullsizeImage = Image.FromFile(sourceFilePath))
        {
            int NewHeight = MaxHeight;
            if (keepAspectRatio)
            {
                NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
                if (NewHeight > MaxHeight)
                {
                    NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
                    NewHeight = MaxHeight;
                }
            }
            using (Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero))
            {
                NewImage.Save(outFilePath, ImageFormat.Png);
            }
        }
    }
    private string GetScreenShotFileName(string url)
    {
        Uri uri = new Uri(url);
        return uri.Host.Replace(".", "_") + uri.LocalPath.Replace("/", "_") + ".png";
    }
    private string GetScreenShotThumbnailFileName(string sourceFilename, int width, int height)
    {
        FileInfo sourceFile = new FileInfo(sourceFilename);
        string shortFilename = sourceFile.Name;
        string ext = Path.GetExtension(shortFilename);
        string replacementEnding = String.Format("{0}x{1}", width, height) + ext;
        return shortFilename.Replace(ext, replacementEnding);
    }
    private string GetRelativeUri(string pathToFile)
    {
        string rootPath = HttpContext.Current.Server.MapPath("~");
        return pathToFile.Replace(rootPath, "").Replace(@"\", "/");
    }
    private bool IsURLValid(string url)
    {
        string strRegex = "^(https?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //user@
+ @"(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP- 199.194.52.184
+ "|" // allows either IP or domain
+ @"([0-9a-z_!~*'()-]+\.)*" // tertiary domain(s)- www.
+ @"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // second level domain
+ "[a-z]{2,6})" // first level domain- .com or .museum
+ "(:[0-9]{1,4})?" // port number- :80
+ "((/?)|" // a slash isn't required if there is no file name
+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
Regex re = new Regex(strRegex, RegexOptions.Compiled | RegexOptions.IgnoreCase);

if (re.IsMatch(url))
return (true);
else
return (false);
} private void SmallThumbnail() { ThumbWidth = 200; ThumbHeight = 150; } private void MediumThumbnail() { ThumbWidth = 240; ThumbHeight = 190; } private void LargeThumbnail() { ThumbWidth = 320; ThumbHeight = 270; } private void SetThumbnailSize() { if (ThumbNailSize == 1) { SmallThumbnail(); } if (ThumbNailSize == 2) { MediumThumbnail(); } if (ThumbNailSize == 3) { LargeThumbnail(); } else { ThumbNailSize = 1; } } }

Tags: , , , ,

ASP.NET | Open Source

Tag cloud

Month List