Sometimes we may have requirement to display image in windows application from URL. For example you are developing C# Windows application and you want to display your company logo on each form. You can directly add the image to your application, but if any changes happen to your company logo you have to add the new logo again to your windows application and have to deploy the code again. Instead of that if you are rending your image from company website, you no need to do any changes even though if there are some changes to logo.
In this article we discuss about how to display the image in C# windows application from URL. Open Microsoft Visual Studio, Create some windows application and name it as CSharpCreateImage.
Add one PictureBox control to your windows form and add below code on your Form load.
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Windows.Forms;
namespace CSharpCreateImage
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string sURL = "http://c.s-microsoft.com/en-in/CMSImages/mslogo.png?version=856673f8-e6be-0476-6669-d5bf2300391d";
WebRequest req = WebRequest.Create(sURL);
WebResponse res = req.GetResponse();
Stream imgStream = res.GetResponseStream();
Image img1 = Image.FromStream(imgStream);
imgStream.Close();
pictureBox1.Image = img1;
}
}
}
The above code using the WebRequest and WebResponse classes to create Stream from the required URL. From the stream we are creating the Image type by using Image.FromStream method, then assigning this image to PictureBox.
Once you run the application, the output displays as shown below.
As shown above we are displaying the Microsoft image from the office Microsoft site.