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

用來建立新 GraphicsImage

傳回

這個方法會傳回指定之 Graphics 的新 Image

例外狀況

imagenull

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

範例

下列程式碼範例是設計來搭配Windows Forms使用,而且需要 PaintEventArgse ,這是事件處理常式的參數 Paint 。 程式碼會執行下列動作:

  • Image從範例資料夾中的圖形檔案SampImag.jpg建立 。

  • GraphicsImage 建立 。

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

  • 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 物件」。索引的像素格式會顯示在下列清單中。

您可以使用 方法將索引影像儲存為另一 Graphics 種格式 Save(String, ImageFormat) ,然後擷取新影像的物件。

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

您應該一律呼叫 Dispose 方法,以釋放 Graphics 方法所 FromImage 建立的 和相關資源。

適用於

另請參閱