Saturn
Saturn

Reputation: 18159

Create Image from Graphics

In VB.NET, I need to create an Image based on a Graphics object I have. However, there is no method such as Image.fromGraphics() etc. What should I do then?

Upvotes: 4

Views: 31721

Answers (2)

Jay Riggs
Jay Riggs

Reputation: 53593

Have a look at the Graphics.DrawImage method and its overloads.

Here's a snippet from one of the examples that draws an image onto the screen, using a Graphics object from Winform's Paint event:

Private Sub DrawImageRect(ByVal e As PaintEventArgs)
    ' Create image.
    Dim newImage As Image = Image.FromFile("SampImag.jpg")

    ' Create rectangle for displaying image.
    Dim destRect As New Rectangle(100, 100, 450, 150)

    ' Draw image to screen.
    e.Graphics.DrawImage(newImage, destRect)
End Sub

Upvotes: 0

Mark Hall
Mark Hall

Reputation: 54562

Try something like this MSDN article states. Essentialy create a Graphics Object from a Bitmap. Then use Graphic methods to do what you need to to the Image and then you can use the Image how you need to. As @Damien_The_Unbeliever stated your Graphics Object is created to enable drawing on another object, it does not have an Image to copy, the object it was created on does.

From above article:

Dim flag As New Bitmap(200, 100)
Dim flagGraphics As Graphics = Graphics.FromImage(flag)
Dim red As Integer = 0
Dim white As Integer = 11
While white <= 100
    flagGraphics.FillRectangle(Brushes.Red, 0, red, 200, 10)
    flagGraphics.FillRectangle(Brushes.White, 0, white, 200, 10)
    red += 20
    white += 20
End While
pictureBox1.Image = flag

Upvotes: 8

Related Questions