語言

Graphics.FromImage(Image) 方法

定義

從指定的 Graphics建立一個新 Image 。

public:
 static System::Drawing::Graphics ^ FromImage(System::Drawing::Image ^ image);
public static System.Drawing.Graphics FromImage(System.Drawing.Image image);
static member FromImage : System.Drawing.Image -> System.Drawing.Graphics
Public Shared Function FromImage (image As Image) As Graphics

參數

image
Image

Image 由此產生新的 Graphics。

傳回

此方法會回傳指定的 GraphicsImage新值。

例外狀況

image 是 null。

image 具有索引像素格式或其格式未定義。

範例

以下程式碼範例是為 Windows Forms 設計的,並需要 PaintEventArgse,這是 Paint 事件處理程序的參數。 程式代碼會執行下列動作:

  • 在範例資料夾中建立 Image from a graphics file SampImag.jpg。

  • 由 Graphics產生 。Image

  • 藉由在影像中填滿矩形來改變影像。

  • 把它 Image 吸引到螢幕上。

  • 釋放被創造 Graphics的。

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( gcnew SolidBrush( Color::Black ), 100, 50, 100, 100 );

      // Draw image to screen.
      e->Graphics->DrawImage( imageFile, PointF(0.0F,0.0F) );

      // Dispose of graphics object.
      delete newGraphics;
   }
private 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));

    // Dispose of graphics object.
    newGraphics.Dispose();
}
Private Sub FromImageImage2(ByVal 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(0.0F, 0.0F))

    ' Dispose of graphics object.
    newGraphics.Dispose()
End Sub

備註

如果影像具有已編製索引的圖元格式,這個方法會擲回含有訊息的例外狀況:「無法從具有索引圖元格式的影像建立 Graphics 物件」。索引像素格式會顯示在下列清單中。

你可以用這個 Save(String, ImageFormat) 方法將索引影像存成另一種格式,然後再取得 Graphics 新影像的物件。

如果影像具有下列任何像素格式,這個方法也會擲回例外狀況。

你應該總是呼叫該 Dispose 方法來釋放 Graphics 該 FromImage 方法所產生的相關資源。

適用於

另請參閱