none
How to save PictureBox image with markups RRS feed

  • Question

  • My application has a PictureBox that is assigned an image and then a rectangle is drawn on top of the image:

    Private Sub myLoad(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
        Dim b as bitmap = ...
        ...
        PictureBox1.Image = b
    End Sub
    
    Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
        Dim b1 As Brush = New SolidBrush(Color.Yellow)
        e.Graphics.FillEllipse(b1, 100, 100, 10, 10)
        e.Graphics.FillEllipse(b1, 300, 300, 10, 10)
        e.Graphics.DrawRectangle(Pens.Yellow, 100, 100, 200, 200)
    End Sub
    

    How do I "capture" the bitmap with the things that have been drawn on it to:
    - Display in a second PictureBox
    - Save to a JPG

    Thursday, December 21, 2017 4:27 PM

Answers

  • Try following code

    Dim bmp as Bitmap= new Bitmap(PictureBox1.ClientSize.Width, PictureBox1.ClientSize.Height)
    PictureBox1.DrawToBitmap(bmp, PictureBox1. ClientRectangle)
    bmp.Save(filepath)


    Gaurav Khanna | Microsoft MVP | Microsoft Community Contributor

    • Proposed as answer by Frank L. Smith Thursday, December 21, 2017 4:47 PM
    • Marked as answer by JellicleMime Thursday, December 21, 2017 6:27 PM
    Thursday, December 21, 2017 4:43 PM

All replies

  • Try following code

    Dim bmp as Bitmap= new Bitmap(PictureBox1.ClientSize.Width, PictureBox1.ClientSize.Height)
    PictureBox1.DrawToBitmap(bmp, PictureBox1. ClientRectangle)
    bmp.Save(filepath)


    Gaurav Khanna | Microsoft MVP | Microsoft Community Contributor

    • Proposed as answer by Frank L. Smith Thursday, December 21, 2017 4:47 PM
    • Marked as answer by JellicleMime Thursday, December 21, 2017 6:27 PM
    Thursday, December 21, 2017 4:43 PM
  • Gaurav,

    Thank you for the quick answer.  I'm curious why I couldn't simply say PictureBox2.image = PictureBox1.Image and have it include the ellipses and rectangle.

    Thanks again.

    Thursday, December 21, 2017 6:29 PM
  • Gaurav,

    Thank you for the quick answer.  I'm curious why I couldn't simply say PictureBox2.image = PictureBox1.Image and have it include the ellipses and rectangle.

    Thanks again.

     Because you are not drawing that stuff on the image that is in the picturebox,  you are drawing it on the PictureBox control itself.  That is why drawing the PictureBox control to a Bitmap and saving it works.

     You could draw the stuff onto the Bitmap Image that is assigned to the PictureBox's Image property,  then save the Bitmap Image.  However,  then you may need to take into account the PictureBox's SizeMode property and any scaling that may or may not need to be done to draw the ellipses and rectangle in the right locations.


    If you say it can`t be done then i`ll try it

    Thursday, December 21, 2017 9:19 PM