hajime_saitou hajime_saitou - 7 months ago 133
Vb.net Question

Resize and Save Image in the Picturebox as PNG

How do I resize to 100px by 100px and save the image in picturebox as a PNG? I can do the saving but the output file won't open. The code I only have is below.

picbox.Image.Save("example_file", System.Drawing.Imaging.ImageFormat.Png)

Answer

The basics for a thumbnail are fairly straight forward:

  1. Create a new bitmap of the desired size
  2. Draw the original to it; By drawing to a smaller BMP, it is thumbnailed

For saving, you might want to add ".png" to the filename. Since your image is in a picbox, get it out for less typing:

Dim bmp As Bitmap = CType(picbox.Image, Bitmap)

' bmpt is the thumbnail
Dim bmpt As New Bitmap(100, 100)
Using g As Graphics = Graphics.FromImage(bmpt)

    ' draw the original image to the smaller thumb
    g.DrawImage(bmp, 0, 0,
                bmpt.Width + 1,
                bmpt.Height + 1)
End Using

bmpt.Save("example_file.PNG", System.Drawing.Imaging.ImageFormat.Png)

Notes:

  1. The Bitmap you create must be disposed of when you are done with it.
    • If saving is all you need to do, add bmpt.Dispose() as the last line.
    • If the above is used as a method to return a thumbnail, the code which gets the new thumbnail must dispose of it.
  2. If the original image is open (such as shown in a PictureBox) you wont be able to save to the same file name. Alter the name slightly such as "myFoo" saved as "myFoo_t".
  3. The code above assumes a square image. If the Height and Width are not the same, you will also need to scale the thumbnail bitmap to prevent the thumbnail from being distorted. That is, calculate either the Height or Width of the new Bitmap from the other.
Comments