Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

WebBrowser shows File-less local Image

5.00/5 (7 votes)
11 Jun 2010CPOL 28.1K  
Showing an image in a WinForm WebBrowser without using files
A System.Windows.Forms.WebBrowser can be used to browse any web page we want, by using its Navigate() method. It can also be used to display information, real or synthetic, to either its DocumentText or DocumentStream property.

One way to make WebBrowser show a document would be to create a big string starting with <html> and adhering to the HTML specifications; then assigning said string to WebBrowser.DocumentText

However browsers such as Internet Explorer, and hence also WebBrowser, have sufficient intelligence to recognize several different data types, so when the web page isn't actually providing a valid HTML document, but just a simple object, such as an image, the browser will recognize it and handle it well.

Here is some demo code, that creates an image in a MemoryStream, and shows it in a little Form+WebBrowser by using the latter's DocumentStream property.

C#
void CreateAndShowImageInFormAndWebBrowser() {
	Form f=new Form();
	// create an image
	Bitmap bm=new Bitmap(200, 200);
	Graphics g=Graphics.FromImage(bm);
	g.FillRectangle(Brushes.Yellow, new Rectangle(20, 20, 160, 160));
	g.DrawString("Hello World!", f.Font, Brushes.Black, 40, 40);
	// store the image in a memory stream
	MemoryStream ms=new MemoryStream();
	bm.Save(ms, ImageFormat.Gif);
	bm.Dispose();
	// create a web browser that displays the stream
	WebBrowser wb=new WebBrowser();
	wb.Bounds=new Rectangle(20, 20, 500, 500);
	ms.Position=0;
	wb.DocumentStream=ms;
	// tada
	f.Size=new Size(600, 600);
	f.Controls.Add(wb);
	f.Show();
}


Warning: you must "rewind" the stream (like a tape recorder!); without the ms.Position=0; statement, the WebBrowser window would remain very blank.

ADDED: image test using <img src="/script/Membership/Uploads/648011/kitten-high-five.jpg" />



:)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)