Showing posts with label Youtube Video Title. Show all posts
Showing posts with label Youtube Video Title. Show all posts

Thursday, 22 May 2014

How to Generate Video Thumbnail with Title from url in C# ASP.NET

In this article, i am going to give overview on how to generate thumbnail dynamically. 
aspx page
<asp:Image ID="imgThumbnail" runat="server" />

aspx.cs page
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindThumbnailWithTitle();
        }
    }

    void BindThumbnailWithTitle()
    {
        string videoUrl = "https://www.youtube.com/watch?v=pA9QUnloZtw";
        imgThumbnail.ImageUrl = GenerateThumbnail(videoUrl);
        GenerateTitle(videoUrl);
    }

    // generate and return thumbnail by just getting the video url
    public string GenerateThumbnail(string videoUrl)
    {
        string imgLink = "http://img.youtube.com/vi/"; // Common part of every thumbnail url
        string[] videoLink = videoUrl.Split(new char[] { '=', '&' }); //Split code part from url
        imgLink = imgLink + videoLink[1] + "/1.jpg"; // '/1.jpg' is to choose thumbnail image
        return imgLink;
    }

    private void GenerateTitle(string url)
    {
        if (!string.IsNullOrEmpty(url))
        {
            string content = string.Empty;
            string firstCharacters = url.Substring(0, 3);
            if (firstCharacters.ToLower() == "www")
            {
                url = "http://" + url;
            }

            if (firstCharacters.ToLower() == "htt" || firstCharacters.ToLower() == "www")
            {
                try
                {
                    WebRequest webRequest = WebRequest.Create(url);
                    WebResponse webResponse = webRequest.GetResponse();
                    StreamReader sr = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
                    content = sr.ReadToEnd();// Content of page

                    //Split the content between the title tag
                    content = content.Substring(content.IndexOf("<title>") + 7);
                    content = content.Substring(0, content.IndexOf("</title>"));

                    //display it by using write method
                    Response.Write(content);
                }

                catch (Exception)
                {
                    content = "Url Provided by you is invalid";
                    Response.Write(content);
                }
            }

            else
            {
                content = "Url Provided by you is invalid";
                Response.Write(content);
                return;
            }
        }
    }


That’s it!!…..Happy Programming...