Article: WebBrowser shows file-less local Image

Home Page


Consultancy

  • Service Vouchers
  • Escrow Service

Shop



Programming
  • Articles
  • Tools
  • Links

Search

 

Contact

 

PHPinfo


$_SERVER







Showing an image in a WinForm WebBrowser without using files

category 'KB', language C#, created 10-Jun-2010, version 3 (11-Jun-2010), by Luc Pattyn

This article also appeared on the CodeProject.


License: The author hereby grants you a worldwide, non-exclusive license to use and redistribute the files and the source code in the article in any way you see fit, provided you keep the copyright notice in place; when code modifications are applied, the notice must reflect that. The author retains copyright to the article, you may not republish or otherwise make available the article, in whole or in part, without the prior written consent of the author.

Disclaimer: This work is provided as is, without any express or implied warranties or conditions or guarantees. You, the user, assume all risk in its use. In no event will the author be liable to you on any legal theory for any special, incidental, consequential, punitive or exemplary damages arising out of this license or the use of the work or otherwise.


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.

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.



Perceler

Copyright © 2012, Luc Pattyn

Last Modified 21-May-2025