Wednesday, January 23, 2013

How to get Images with pagination using live url, asp.net and c#

GetImages
In this article i would like to explain the procedure of how to get Images with url using asp.net and c# In my previous articles i already explained about How to get the Title and Meta Tags with url using asp.net and c# Basic comments section using Asp.net and c# , Tracking User information using Asp.net and c# and Currency converter application using Asp.net and c# 

Here i am going to explain how to fetch the images with live url, just like in facebook.
So lets start 
facebook_login_button
First Open the visual studio asp.net and select one new website 
Next,Add 1 Textbox control to Default.aspx page for URL entry 
Next,Add the Listview in order to display the images 
Next Add the following code in default.aspx for listview pagination





Next,Call the following method in textchanged Event of URL textbox
 protected void txtFetchURL_TextChanged(object sender, EventArgs e)
    {
        //Get the url
         String url = txtURL.Text;
                 
        //Method to get Meta Tags
        GetImages();
    }

Next, write the following code in GetImages Method
private void GetImages()
{
        //Get Images
        lvImages.DataSource = SampleData();
        lvImages.DataBind();
}
Next,Add the following code in sample data
 List SampleData()
    {
        List p = new List();

        ImageButton[] imgval = new ImageButton[50];
        int i = 0;

        foreach (string image in FetchImages(txtFetchURL.Text))
        {
            imgval[i] = new ImageButton();
            imgval[i].ImageUrl = image;

            if (imgval[i] != null)
            {
                p.Add(new Product() { Name = image });
            }

            i++;
        }
        return p;
    }
    public class Product
    {
        public string Name { get; set; }
    }

    public List FetchImages(string Url)
    {
        List imageList = new List();

        //Append http:// if necessary
        if (!Url.StartsWith("http://") && !Url.StartsWith("https://"))
            Url = "http://" + Url;

        string responseUrl = string.Empty;
        string htmlData = ASCIIEncoding.ASCII.GetString(DownloadData(Url, out responseUrl));

        if (responseUrl != string.Empty)
            Url = responseUrl;

        if (htmlData != string.Empty)
        {
            string imageHtmlCode = "'); //make sure data will be inside img tag
                int start = htmlData.IndexOf(imageSrcCode) + imageSrcCode.Length;
                int end = htmlData.IndexOf('"', start + 1);

                //Extract the line
                if (end > start && start < brackedEnd)
                {
                    string loc = htmlData.Substring(start, end - start);

                    //Store line
                    imageList.Add(loc);
                }

                //Move index to next image location
                if (imageHtmlCode.Length < htmlData.Length)
                    index = htmlData.IndexOf(imageHtmlCode, imageHtmlCode.Length);
                else
                    index = -1;
            }

            //Format the image URLs
            for (int i = 0; i < imageList.Count; i++)
            {
                string img = imageList[i];

                string baseUrl = GetBaseURL(Url);

                if ((!img.StartsWith("http://") && !img.StartsWith("https://")) && baseUrl != string.Empty)
                    img = baseUrl + "/" + img.TrimStart('/');

                imageList[i] = img;
            }
        }

        return imageList;
    }

    
private byte[] DownloadData(string Url)
    {
        string empty = string.Empty;
        return DownloadData(Url, out empty);
    }
    private byte[] DownloadData(string Url, out string responseUrl)
    {
        byte[] downloadedData = new byte[0];
        try
        {
            //Get a data stream from the url
            WebRequest req = WebRequest.Create(Url);
            WebResponse response = req.GetResponse();
            Stream stream = response.GetResponseStream();

            responseUrl = response.ResponseUri.ToString();

            //Download in chuncks
            byte[] buffer = new byte[1024];

            //Get Total Size
            int dataLength = (int)response.ContentLength;

            //Download to memory
            //Note: adjust the streams here to download directly to the hard drive
            MemoryStream memStream = new MemoryStream();
            while (true)
            {
                //Try to read the data
                int bytesRead = stream.Read(buffer, 0, buffer.Length);

                if (bytesRead == 0)
                {
                    break;
                }
                else
                {
                    //Write the downloaded data
                    memStream.Write(buffer, 0, bytesRead);
                }
            }

            //Convert the downloaded stream to a byte array
            downloadedData = memStream.ToArray();

            //Clean up
            stream.Close();
            memStream.Close();
        }
        catch (Exception)
        {
            responseUrl = string.Empty;
            return new byte[0];
        }

        return downloadedData;
    }
    private System.Drawing.Image ImageFromURL(string Url)
    {
        byte[] imageData = DownloadData(Url);
        System.Drawing.Image img = null;

        try
        {
            MemoryStream stream = new MemoryStream(imageData);
            img = System.Drawing.Image.FromStream(stream);
            stream.Close();
        }
        catch (Exception)
        {

        }
        return img;
    }
    private string GetBaseURL(string Url)
    {
        int inx = Url.IndexOf("://") + "://".Length;
        int end = Url.IndexOf('/', inx);

        string baseUrl = string.Empty;
        if (end != -1)
            return Url.Substring(0, end);
        else
            return string.Empty;
    }
Next, write the following code in MetaTags Method For pagination, 
Add the following event
protected void pagerTop_OnPrerender(object sender, EventArgs e)
    {
        GetImages();
    }
I hope this article will helps you..if you need any help share your valuable comments..Happy coding

Labels: , , , , ,