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の作成元。

返品

このメソッドは、指定したImageの新しいGraphicsを返します。

例外

imagenullです。

image がインデックス付きピクセル形式であるか、その形式が未定義です。

次のコード例は、Windows Formsで使用するように設計されており、PaintEventArgse が必要です。これは、Paint イベント ハンドラーのパラメーターです。 このコードでは、次のアクションが実行されます。

  • サンプル フォルダー内のグラフィックス ファイル SampImag.jpg から Image を作成します。

  • ImageからGraphicsを作成します。

  • 画像内の四角形を塗りつぶして画像を変更します。

  • 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

注釈

イメージにインデックス付きピクセル形式がある場合、このメソッドは"A Graphics object cannot be created from a image that has an indexed pixel format" (グラフィックス オブジェクトはインデックス付きピクセル形式の画像から作成できません) というメッセージで例外をスローします。インデックス付きピクセル形式を次の一覧に示します。

Save(String, ImageFormat) メソッドを使用してインデックス付きイメージを別の形式で保存し、新しいイメージのGraphics オブジェクトを取得できます。

このメソッドは、画像に次のいずれかのピクセル形式がある場合にも例外をスローします。

FromImage メソッドによって作成されたGraphicsと関連リソースを解放するには、常に Dispose メソッドを呼び出す必要があります。

適用対象

こちらもご覧ください