FromImage Method

Graphics.FromImage Method

Creates a new Graphics object from the specified Image object.

[Visual Basic]
Public Shared Function FromImage( _
   ByVal image As Image _
) As Graphics
public static Graphics FromImage(
 Image image
public: static Graphics* FromImage(
 Image* image
public static function FromImage(
   image : Image
) : Graphics;


Image object from which to create the new Graphics object.

Return Value

This method returns a new Graphics for the specified Image object.


If the image has an indexed pixel format, this method throws an exception with the message, "A Graphics object cannot be created from an image that has an indexed pixel format." The indexed pixel formats are shown in the following list.

  • PixelFormat.Format1bppIndexed
  • PixelFormat.Format4bppIndexed
  • PixelFormat.Format8bppIndexed

This method also throws an exception if the image has any of the following pixel formats.

  • PixelFormat.Undefined
  • PixelFormat.DontCare
  • PixelFormat.Format16bppArgb1555
  • PixelFormat.Format16bppGrayScale


[Visual Basic, C#] The following example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler. The code performs the following action:

  • Creates an Image object from a graphics file SampImag.jpg in the example folder.
  • Creates a Graphics object from the Image object.
  • Alters the image by filling a rectangle within it.
  • Draws the Image object to the screen.
  • Releases the created Graphics object.
[Visual Basic] 
Public Sub FromImageImage(e As PaintEventArgs)
' Create image.
Dim imageFile As Image = Image.FromFile("SampImag.jpg")
' Create graphics object for alteration.
Dim newGraphics As Graphics = Graphics.FromImage(imageFile)
' Alter image.
newGraphics.FillRectangle(New SolidBrush(Color.Black), _
100, 50, 100, 100)
' Draw image to screen.
e.Graphics.DrawImage(imageFile, New PointF(0F, 0F))
' Dispose of graphics object.
End Sub
public void FromImageImage(PaintEventArgs e)
// Create image.
Image imageFile = Image.FromFile("SampImag.jpg");
// Create graphics object for alteration.
Graphics newGraphics = Graphics.FromImage(imageFile);
// Alter image.
newGraphics.FillRectangle(new SolidBrush(Color.Black), 100, 50, 100, 100);
// Draw image to screen.
e.Graphics.DrawImage(imageFile, new PointF(0.0F, 0.0F));
// Release graphics object.

[C++, JScript] No example is available for C++ or JScript. To view a Visual Basic or C# example, click the Language Filter button Language Filter in the upper-left corner of the page.


Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

See Also

Graphics Class | Graphics Members | System.Drawing Namespace

© 2016 Microsoft