3 Mar 2016

youtube video thumbnail generator asp.net c#

here i explained how to add  youtube video thumbnail without uploading image

.CS code 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Here we are binding static urls, you can also bind from database table
            DataTable dt = new DataTable();
            dt.Columns.Add("YoutubeVideoURL");
            DataRow dr= dt.NewRow();
            DataRow dr1= dt.NewRow();
            dr["YoutubeVideoURL"] = "https://www.youtube.com/watch?v=testis";
            dr1["YoutubeVideoURL"] = "https://www.youtube.com/watch?v=testid";
            dt.Rows.Add(dr);
            dt.Rows.Add(dr1);
            rpt.DataSource=dt;
            rpt.DataBind();
        
       
        }
    }
    protected string CreateVideoThumbnail(string YoutubeUrl)
    {
        string youTubeThumb = string.Empty;
        if (YoutubeUrl == "")
            return "";

        if (YoutubeUrl.IndexOf("=") > 0)
        {
            youTubeThumb = YoutubeUrl.Split('=')[1];
        }
        else if (YoutubeUrl.IndexOf("/v/") > 0)
        {
            string strVideoCode = YoutubeUrl.Substring(YoutubeUrl.IndexOf("/v/") + 3);
            int ind = strVideoCode.IndexOf("?");
            youTubeThumb = strVideoCode.Substring(0, ind == -1 ? strVideoCode.Length : ind);
        }
        else if (YoutubeUrl.IndexOf('/') < 6)
        {
            youTubeThumb = YoutubeUrl.Split('/')[3];
        }
        else if (YoutubeUrl.IndexOf('/') > 6)
        {
            youTubeThumb = YoutubeUrl.Split('/')[1];
        }

        return "http://img.youtube.com/vi/" + youTubeThumb + "/mqdefault.jpg";
    }    
}

===============================================
.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Repeater ID="rpt" runat="server">
    <ItemTemplate>
    <a href='<%#Eval("YoutubeVideoURL") %>'"> <asp:Image ID="Image1" src='<%# CreateVideoThumbnail((Eval("YoutubeVideoURL").ToString())) %>' runat="server" /> </a> <br />

    </ItemTemplate>
    </asp:Repeater>
      
   
    </form>
</body>
</html>



No comments:

Post a Comment