How to: Display Images with the .NET Framework

 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

For the latest documentation on Visual Studio 2017, see How to: Display Images with the .NET Framework on docs.microsoft.com.

The following code example modifies the OnPaint event handler to retrieve a pointer to the Graphics object for the main form. The OnPaint function is intended for a Windows Forms application, most likely created with a Visual Studio application wizard.

The image is represented by the Image class. The image data is loaded from a .jpg file using the Image.FromFile method. Before the image is drawn to the form, the form is resized to accommodate the image. The drawing of the image is performed with the Graphics.DrawImage method.

The Graphics and Image classes are both in the System.Drawing namespace.

Note

GDI+ is included with Windows XP and is available as a redistributable for Windows NT 4.0 SP 6, Windows 2000, Windows 98, and Windows Me. To download the latest redistributable, see https://go.microsoft.com/fwlink/?linkid=11232.

Example

#using <system.drawing.dll>  
  
using namespace System;  
using namespace System::Drawing;  
  
protected:  
virtual Void Form1::OnPaint(PaintEventArgs^ pe) override  
{  
    Graphics^ g = pe->Graphics;  
    Image^ image = Image::FromFile("SampleImage.jpg");  
    Form::ClientSize = image->Size;  
    g->DrawImage( image, 0, 0, image->Size.Width, image->Size.Height );  
}  

See Also

System.Drawing
.NET Programming with C++/CLI (Visual C++)