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 窗体 一起使用,它需要 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 方法来释放 GraphicsFromImage 方法创建的 和相关资源。

适用于

另请参阅