Private _BaseImage As Image
Private _AddImage As Image
Public Property EmptyBitmapSize As New Size(500, 500)
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
PictureBox1.SizeMode = PictureBoxSizeMode.AutoSize
PictureBox1.BorderStyle = BorderStyle.Fixed3D
ZoomPictureBox1.Parent = PictureBox1
ZoomPictureBox1.BackColor = Color.Transparent
ZoomPictureBox1.BorderStyle = BorderStyle.None
ZoomPictureBox1.Bounds = PictureBox1.ClientRectangle
End Sub
'Keep the ZoomPictureBox aligned to the PictureBox:
Private Sub PictureBox1_SizeChanged(sender As Object, e As System.EventArgs) Handles PictureBox1.SizeChanged
ZoomPictureBox1.Bounds = PictureBox1.ClientRectangle
End Sub
Private Sub ZoomPictureBox1_DoubleClick(sender As Object, e As System.EventArgs) Handles ZoomPictureBox1.DoubleClick
PictureBox1.Image = SuperimposeImage(_BaseImage, _AddImage, ZoomPictureBox1.ImagePosition, ZoomPictureBox1.ZoomFactor)
End Sub
'Get the base image for the PictureBox (or an empty bitmap)
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
_BaseImage = GetImage(EmptyBitmapSize, "Select base image")
PictureBox1.Image = _BaseImage
End Sub
'Get a image for the ZoomPictureBox
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
_AddImage = GetImage(EmptyBitmapSize, "Select zoomable image")
ZoomPictureBox1.Image = _AddImage
End Sub
'Save the resulting image
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
SaveImage(_BaseImage)
End Sub
'Get an image from file or an empty bitmap:
Private Function GetImage(emptyBitmapSize As Size, caption As String) As Image
Dim bmp As New Bitmap(emptyBitmapSize.Width, emptyBitmapSize.Height)
Using ofd As New OpenFileDialog With {.Title = caption}
If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
Try
bmp = New Bitmap(ofd.FileName)
Catch
MessageBox.Show("Invalid image file " & ofd.FileName)
End Try
End If
End Using
Return bmp
End Function
'Superimpose an image on the base image at a given position and magnfication:
Private Function SuperimposeImage(baseImage As Image, addImage As Image, location As Point, zoomFactor As Double) As Image
Using g As Graphics = Graphics.FromImage(baseImage)
g.DrawImage(addImage, location.X, location.Y, _
CInt(addImage.Width * zoomFactor), _
CInt(addImage.Height * zoomFactor))
End Using
Return baseImage
End Function
'Save the resulting base image:
Private Sub SaveImage(img As Image)
Using sfd As New SaveFileDialog With {.Filter = "Image Files (*.png, *.jpg)|*.png;*.jpg"}
If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
If sfd.FileName.ToUpper.EndsWith("PNG") Then
_BaseImage.Save(sfd.FileName, Imaging.ImageFormat.Png)
ElseIf sfd.FileName.ToUpper.EndsWith("JPG") Then
_BaseImage.Save(sfd.FileName, Imaging.ImageFormat.Jpeg)
Else
MessageBox.Show("Please give a PNG or JPG extension. Other formats are not yet supported.")
End If
End If
End Using
End Sub