locked
Code Snippet: Retrieve an Image from HTML Source RRS feed

  • Question

  • User-1871612231 posted

    // This code snippet can be used to retrieve any image from any HTML content or source
    //If youre' having any problem in coding, you can download the sample project I have written in C# (.net 2008-SP1)
    //I hope you'll like this code snippet and I know It can be written much more flexible without writing all those extensions. But to save time and energy I did it in such a way that I can achieve my goal //easily...hehe

     

     

    using System.Text;
    
            private void button1_Click(object sender, EventArgs e)
            {
    
                label2.Text  = getHTMLImage("WRITE YOUR HTML SOURCE HERE WHICH CONTAINS A <IMG> TAG");
    
            }
    
    
            protected virtual String getHTMLImage(string Body) {
    
    
                String bodyX = Body.ToLower();
               
                int getPosition = -1;
                int getPositionY = -1;
                String Extension = "";
    
    
                getPositionY = bodyX.IndexOf("src=");
    
                //-----------------------------------------------------
    
                //1st phaze
                String ImagePath = bodyX.Remove(0, getPositionY + 5);
    
                //2nd phaze
                if (getPosition == -1)
                {
                    getPosition = ImagePath.IndexOf(".jpg" + '"');
                    Extension = ".jpg";
                }
    
                if (getPosition == -1)
                {
    
                    getPosition = ImagePath.IndexOf(".png" + '"');
                    Extension = ".png";
                }
    
                if (getPosition == -1)
                {
    
                    getPosition = ImagePath.IndexOf(".jpeg" + '"');
                    Extension = ".jpeg";
                }
               
                if (getPosition == -1)
                {
    
                    getPosition = ImagePath.IndexOf(".gif" + '"');
                    Extension = ".gif";
                }
              
                if (getPosition == -1)
                {
    
                    getPosition = ImagePath.IndexOf(".bmp" + '"');
                    Extension = ".bmp";
                }
    
                try
                {
                    ImagePath = ImagePath.Remove(getPosition, ImagePath.Length - getPosition);
              
                }
                catch {
                    ImagePath = "no Image in the HTML Code";
                    Extension = "";
                }
    
                return ImagePath + Extension;
             }
    
      
    Sunday, December 7, 2008 10:29 PM

All replies