Thursday, 3 May 2012

Loading WebImages onto the Windows Application

Hi,

Here is the solution for loading webimages onto the windows application.

1) The first thing that we need is to create a HttpWebRequest object from the Image URL.
2) GetResponse will get the resulting response from the request we have made.
3) From GetResponseStream method of HttpWebResponse we can get the Stream of the URL.
4) After getting the Stream objtect, create an Image object from it.
 
        private Image GetImageFromWeb(string strURL)
        {
            Stream streamImage = null;
            try
            {
                //Create a web request to the url containing the image
                HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(strURL);
                //gets the response from the web request
                HttpWebResponse wRes = (HttpWebResponse)(wReq).GetResponse();
                //return the image stream from the URL specified earlier
                streamImage = wRes.GetResponseStream();
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }

            if (streamImage != null)
            {
                return Image.FromStream(streamImage);
            }
            else
            {
                return null;
            }
        }

Now you got the image, you can give it to the picturebox and that will display the image.
Lets say, we have pbxImage(PictureBox) is there on the form.
then just the write the below line in your code, that will load the image from the web.
                  string strURL = "<URL of the Image>";
                 pbxImage .Image = GetImageFromWeb(strURL);

Hope this helps

--
Happy Coding
Gopinath

1 comment:

  1. This is the information that I was looking for.. Thanks for the efforts you put to gather such a nice content and posted here.Please stay us informed like this.
    AX Training | Microsoft Dynamics CRM Online Training

    ReplyDelete