Memanipulasi Kontrol PictureBox di Visual Basic .NET (VB.NET)

PictureBox merupakan salah satu kontrol form yang ada di toolbox yang berfungsi untuk menampilkan gambar ke dalam Form. Selain menampilkan gambar secara statis gambar dalam picturebox juga bisa kita manipulasi untuk berbagai keperluan misalnya mengubah ukuran gambar, merubah warna gambar, me-rotate (memutar) atau efek sederhana lainya misalnya menambahkan watermark dan lain sebagainya.

Dalam artikel kali ini admin akan membuat sebuah Aplikasi sederhana untuk manipulasi kontrol picturebox dengan beberapa manipulasi diantaranya :

1. Mengambil Gambar 

2. Memutar Gambar (rotate)

3. Memberi Warna Gray 

4. Crop (memotong)

5. Undo

6. Menyimpan Gambar

Manipulasi PictureBox VB.net



Apa itu PictureBox di VB.NET?

PictureBox adalah kontrol pada Windows Forms yang digunakan untuk menampilkan gambar dari berbagai format, seperti JPG, PNG, GIF, dan BMP. Kontrol ini fleksibel dan sangat membantu ketika kita ingin menambahkan elemen visual di aplikasi. Dengan VB.NET, kamu bisa melakukan banyak hal dengan PictureBox, mulai dari menampilkan gambar statis hingga membuat animasi sederhana.

Beberapa kelebihan PictureBox:

  • Mudah digunakan dan di-drag langsung dari Toolbox.
  • Bisa menampilkan berbagai format gambar.
  • Mendukung manipulasi ukuran, posisi, dan event klik.
  • Cocok untuk aplikasi interaktif.


Cara menambahkan PictureBox dan komponen lainnya

1. Buka Microsoft Visual Studio Anda

2. Klik Create a New Project

3. Cari template Windows Form App (WinForms) dan klik templatenya

4. Klik Next

5. Ketik nama Project > Folder Peyimpanan

6. Klik Next

7. Pilih Framework .NET 6.0

8. Klik Create (tunggu...sampai Form1 muncul)

9. Di Form1 tanamkan beberapa kontrol diantaranya :

  • PictureBox  >> Name:PictureBox1 >> SizeMode:Zoom >> BorderStyle:FixedSingle
  • OpenFileDialog >> Name:OpenFileDialog1
  • SaveFileDialog >> Name:SaveFileDialog1
  • 6 Button terdiri dari :
    • Button1 >> Caption:"Load Gambar" Name:btnLoad
    • Button2 >> Caption:"Rotate" Name:btnRotate
    • Button3 >> Caption:"Gray" Name:btnGray
    • Button4 >> Caption:"Crop" Name:btnCrop
    • Button5 >> Caption:"Undo" Name:btnUndo
    • Button6 >> Caption:"Save" Name:btnSave

10. Desainlah Form seperti gambar dibawah ini :


Setelah mendesain Form seperti diatas copy kode dibawah ini :

Public Class Form1


    ' ================= VARIABEL =================

    Dim currentImage As Bitmap

    Dim undoImage As Bitmap


    Dim isCropping As Boolean = False

    Dim isDraggingCrop As Boolean = False

    Dim startPoint As Point

    Dim currentPoint As Point

    Dim cropRectPB As Rectangle   ' untuk tampilan (PictureBox)

    Dim cropRectImg As Rectangle  ' untuk image pixel


    ' ================= FORM LOAD =================

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        PictureBox1.SizeMode = PictureBoxSizeMode.Zoom

        PictureBox1.BorderStyle = BorderStyle.FixedSingle


        btnUndo.Enabled = False

    End Sub


    '1. ================= LOAD IMAGE =================

    Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click

        Using ofd As New OpenFileDialog

            ofd.Filter = "Image Files|*.jpg;*.png;*.bmp"

            If ofd.ShowDialog = DialogResult.OK Then

                currentImage = New Bitmap(ofd.FileName)

                PictureBox1.Image = currentImage

                btnUndo.Enabled = False

            End If

        End Using

    End Sub


    ' 2.================= Membuat tombol Undo =================

    Private Sub btnUndo_Click(sender As Object, e As EventArgs) Handles btnUndo.Click

        If undoImage IsNot Nothing Then

            currentImage = CType(undoImage.Clone(), Bitmap)

            PictureBox1.Image = currentImage

            btnUndo.Enabled = False

        End If

    End Sub


    '3. ================= Kode tombol Crop =================

    Private Sub btnCrop_Click(sender As Object, e As EventArgs) Handles btnCrop.Click

        If currentImage Is Nothing Then Exit Sub

        isCropping = True

        PictureBox1.Cursor = Cursors.Cross

    End Sub


    ' ================= Mouse Down =================

    Private Sub PictureBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseDown

        If Not isCropping OrElse currentImage Is Nothing Then Exit Sub


        isDraggingCrop = True

        startPoint = e.Location

        currentPoint = e.Location

    End Sub


    ' ================= Mouse Move =================

    Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseMove

        If isDraggingCrop Then

            currentPoint = e.Location


            cropRectPB = New Rectangle(

                Math.Min(startPoint.X, currentPoint.X),

                Math.Min(startPoint.Y, currentPoint.Y),

                Math.Abs(currentPoint.X - startPoint.X),

                Math.Abs(currentPoint.Y - startPoint.Y)

            )


            PictureBox1.Invalidate()

        End If

    End Sub


    ' ================= PAINT (KOTAK DRAG) =================

    Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint

        If isDraggingCrop Then

            Using pen As New Pen(Color.Red, 2)

                pen.DashStyle = Drawing2D.DashStyle.Dash

                e.Graphics.DrawRectangle(pen, cropRectPB)

            End Using

        End If

    End Sub


    ' ================= MOUSE UP (EKSEKUSI CROP) =================

    Private Sub PictureBox1_MouseUp(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseUp

        If Not isDraggingCrop OrElse currentImage Is Nothing Then Exit Sub


        isDraggingCrop = False

        isCropping = False

        PictureBox1.Cursor = Cursors.Default


        If cropRectPB.Width < 5 Or cropRectPB.Height < 5 Then

            PictureBox1.Invalidate()

            Exit Sub

        End If


        ' SIMPAN UNDO

        undoImage = CType(currentImage.Clone(), Bitmap)


        ' KONVERSI KE IMAGE PIXEL

        Dim p1 As Point = PictureBoxToImage(startPoint)

        Dim p2 As Point = PictureBoxToImage(currentPoint)


        cropRectImg = New Rectangle(

            Math.Min(p1.X, p2.X),

            Math.Min(p1.Y, p2.Y),

            Math.Abs(p2.X - p1.X),

            Math.Abs(p2.Y - p1.Y)

        )


        ' VALIDASI

        If cropRectImg.Width <= 0 Or cropRectImg.Height <= 0 Then Exit Sub


        ' CROP IMAGE

        Dim croppedBitmap As New Bitmap(cropRectImg.Width, cropRectImg.Height)

        Using g As Graphics = Graphics.FromImage(croppedBitmap)

            g.DrawImage(currentImage,

                        New Rectangle(0, 0, croppedBitmap.Width, croppedBitmap.Height),

                        cropRectImg,

                        GraphicsUnit.Pixel)

        End Using


        currentImage = croppedBitmap

        PictureBox1.Image = currentImage

        btnUndo.Enabled = True

        PictureBox1.Invalidate()

    End Sub


    ' ================= KONVERSI =================

    Function GetImageRectangle() As Rectangle

        Dim imgRatio As Single = currentImage.Width / currentImage.Height

        Dim boxRatio As Single = PictureBox1.Width / PictureBox1.Height


        Dim drawW, drawH, offsetX, offsetY As Integer


        If imgRatio > boxRatio Then

            drawW = PictureBox1.Width

            drawH = CInt(PictureBox1.Width / imgRatio)

            offsetX = 0

            offsetY = (PictureBox1.Height - drawH) \ 2

        Else

            drawH = PictureBox1.Height

            drawW = CInt(PictureBox1.Height * imgRatio)

            offsetY = 0

            offsetX = (PictureBox1.Width - drawW) \ 2

        End If


        Return New Rectangle(offsetX, offsetY, drawW, drawH)

    End Function


    Function PictureBoxToImage(pt As Point) As Point

        Dim imgRect = GetImageRectangle()


        Dim x = CInt((pt.X - imgRect.X) * currentImage.Width / imgRect.Width)

        Dim y = CInt((pt.Y - imgRect.Y) * currentImage.Height / imgRect.Height)


        x = Math.Max(0, Math.Min(x, currentImage.Width - 1))

        y = Math.Max(0, Math.Min(y, currentImage.Height - 1))


        Return New Point(x, y)

    End Function


  ' 4. =================TOMBOL ROTATE =================

    Private Sub btnRotate_Click(sender As Object, e As EventArgs) Handles btnRotate.Click

        If currentImage Is Nothing Then Exit Sub


        ' SIMPAN UNDO

        undoImage = CType(currentImage.Clone(), Bitmap)


        ' BUAT BITMAP BARU

        Dim rotatedBitmap As New Bitmap(currentImage)

        rotatedBitmap.RotateFlip(RotateFlipType.Rotate90FlipNone)


        ' ASSIGN ULANG

        currentImage = rotatedBitmap

        PictureBox1.Image = currentImage

        btnUndo.Enabled = True

        PictureBox1.Invalidate()

    End Sub

  '5.  ================= TOMBOL GREY =================

    Private Sub btnGray_Click(sender As Object, e As EventArgs) Handles btnGray.Click

        If currentImage Is Nothing Then Exit Sub


        ' SIMPAN UNDO

        undoImage = CType(currentImage.Clone(), Bitmap)


        ' BITMAP BARU

        Dim grayBitmap As New Bitmap(currentImage.Width, currentImage.Height)


        For y As Integer = 0 To currentImage.Height - 1

            For x As Integer = 0 To currentImage.Width - 1

                Dim c As Color = currentImage.GetPixel(x, y)


                Dim grayValue As Integer =

                    (CInt(c.R) + CInt(c.G) + CInt(c.B)) \ 3


                grayBitmap.SetPixel(x, y,

                    Color.FromArgb(grayValue, grayValue, grayValue))

            Next

        Next


        ' ASSIGN ULANG

        currentImage = grayBitmap

        PictureBox1.Image = currentImage

        btnUndo.Enabled = True

        PictureBox1.Invalidate()

    End Sub

  ' 6. ================= TOMBOL SAVE =================

    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click

        If currentImage Is Nothing Then

            MessageBox.Show("Belum ada gambar", "Info")

            Exit Sub

        End If


        SaveFileDialog1.Filter = "PNG Image|*.png|JPEG Image|*.jpg|Bitmap Image|*.bmp"

        SaveFileDialog1.Title = "Simpan Gambar"


        If SaveFileDialog1.ShowDialog() = DialogResult.OK Then

            currentImage.Save(SaveFileDialog1.FileName)

            MessageBox.Show("Gambar berhasil disimpan", "Sukses")

        End If

    End Sub


End Class

11. Setelah itu buka jendela kode lalu hapus semua kode yang ada dengan CTRL+A dan tekan Del kemudian Paste kode diatas.

Jalankan Project Anda, coba uji coba tiap tombol.

Kesimpulan

PictureBox adalah salah satu kontrol paling fleksibel di VB.NET. Selain untuk menampilkan gambar, kontrol ini bisa dimanipulasi untuk interaktivitas, animasi sederhana, dan efek visual. Mulai dari mengubah gambar, menangani klik, sampai memodifikasi ukuran dan posisi, semua bisa dilakukan dengan mudah.
\
Demikianlah artikel singkat tentang Memanipulasi Kontrol PictureBox di Visual Basic .NET (VB.NET), semoga artikel ini bermanfaat buat kita semua.Amin.

Selamat mencoba semoga berhasil.

Post a Comment for "Memanipulasi Kontrol PictureBox di Visual Basic .NET (VB.NET)"