Hassan's profileDhicrypt's Live SpaceBlogListsGuestbookMore ![]() | Help |
|
|
December 02 Code Snipset: Retrieve an Image from HTML Source Hi friends, after a long time...again today I'm back to you guys with a simple code snippet, which I have written for a website. But I just thought to share this with you guys... I know its simple but a very useful code snippet when you want to retrieve an image from any HTML content. So lets begin, using System.Text; ///This is the main part of this snippet. ///At first I have setup a string called bodyX which will get the input text(HTML source) and it will change its case to simple for easier use and to avoid case problems. ///int getPositionY is used to find the starting position of the first 'src=' from the HTML content. We very well know that mainly in HTML codes, src is use to mention the path of Image. ///int getPosition is used to find the starting position of the extension of image. ///now we can easily get the starting position and ending position of the first image tag in html. And by removing characters and applying a simple formula we can extract the image from the content. ///Anyways dont worry about the code snippet. juz copy paste it and have a look on the code written under the Button click event. And also it would be useful if you review the codes I;v written in getHTMLImage function. 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; } private void button1_Click(object sender, EventArgs e) { label2.Text = getHTMLImage(lblhtml.text); } 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 |
|
|