NEWS

Image Crop (Cắt ảnh đơn giản) với VB.NET

Image Crop (Cắt ảnh đơn giản) với VB.NET
Đăng bởi: Hoàng Tử Nhỏ - Lượt xem: 16197 20:49:16, 12/11/2015VB.NET   In bài viết

Hôm nay lang thang trên internet thấy có đoạn code cắt ảnh khá đơn giản, mình rãnh viết demo cho các bạn tham khảo. Ý tưởng ở công cụ này cũng tương tự như những phần mềm cắt ảnh chuyên nghiệp khác là dùng chuột đánh dấu vùng ảnh cần để cắt. Sau khi đánh dấu được vùng chọn thì bạn lưu lại. Bạn thiết kế form như mình sau:

Image cropping with VB.NET

- Sau khi bạn thiết kế form như trên mình sẽ tiến hành code tuần tự cho các chức năng cắt ảnh, như phần giới thiệu phía trên chủ yếu mình làm việc với các sự kiện đến Mouse. Mình sẽ lần lượt viết các sự kiện liên quan.

Private Sub picCrop_MouseDown(sender As Object, e As MouseEventArgs) Handles picCrop.MouseDown
        Try

            If e.Button = Windows.Forms.MouseButtons.Left Then

                cropX = e.X
                cropY = e.Y

                cropPen = New Pen(cropPenColor, cropPenSize)
                cropPen.DashStyle = DashStyle.DashDotDot
                Cursor = Cursors.Cross

            End If
            picCrop.Refresh()
        Catch exc As Exception
        End Try
End Sub
 Private Sub picCrop_MouseMove(sender As Object, e As MouseEventArgs) Handles picCrop.MouseMove
        Try

            If picCrop.Image Is Nothing Then Exit Sub

            If e.Button = Windows.Forms.MouseButtons.Left Then

                picCrop.Refresh()
                cropWidth = e.X - cropX
                cropHeight = e.Y - cropY
                picCrop.CreateGraphics.DrawRectangle(cropPen, cropX, cropY, cropWidth, cropHeight)
            End If
            ' GC.Collect()

        Catch exc As Exception

            If Err.Number = 5 Then Exit Sub
        End Try
End Sub
 Private Sub picCrop_MouseUp(sender As Object, e As MouseEventArgs) Handles picCrop.MouseUp
        Try
            Cursor = Cursors.Default
            Try

                If cropWidth < 1 Then
                    Exit Sub
                End If

                Dim rect As Rectangle = New Rectangle(cropX, cropY, cropWidth, cropHeight)
                Dim bit As Bitmap = New Bitmap(picCrop.Image, picCrop.Width, picCrop.Height)

                cropBitmap = New Bitmap(cropWidth, cropHeight)
                Dim g As Graphics = Graphics.FromImage(cropBitmap)
                g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                g.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
                g.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
                g.DrawImage(bit, 0, 0, rect, GraphicsUnit.Pixel)
                picPreview.Image = cropBitmap

            Catch exc As Exception
            End Try
        Catch exc As Exception
        End Try
End Sub

- Sau khi xác đinh được vị trí hình ảnh cần cắt. Bây giờ tiến hành lưu lại hình được cắt. Trước tiên bạn hay viết cho mình hàm lưu lại hình ảnh được cắt như sau:

Public Function SavePhoto(ByVal src As Image, ByVal dest As String, ByVal w As Integer) As Boolean
        Try
            Dim imgTmp As System.Drawing.Image
            Dim imgFoto As System.Drawing.Bitmap

            imgTmp = src
            imgFoto = New System.Drawing.Bitmap(w, 225)
            Dim recDest As New Rectangle(0, 0, w, imgFoto.Height)
            Dim gphCrop As Graphics = Graphics.FromImage(imgFoto)
            gphCrop.SmoothingMode = SmoothingMode.HighQuality
            gphCrop.CompositingQuality = CompositingQuality.HighQuality
            gphCrop.InterpolationMode = InterpolationMode.High

            gphCrop.DrawImage(imgTmp, recDest, 0, 0, imgTmp.Width, imgTmp.Height, GraphicsUnit.Pixel)

            Dim myEncoder As System.Drawing.Imaging.Encoder
            Dim myEncoderParameter As System.Drawing.Imaging.EncoderParameter
            Dim myEncoderParameters As System.Drawing.Imaging.EncoderParameters

            Dim arrayICI() As System.Drawing.Imaging.ImageCodecInfo = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()
            Dim jpegICI As System.Drawing.Imaging.ImageCodecInfo = Nothing
            Dim x As Integer = 0
            For x = 0 To arrayICI.Length - 1
                If (arrayICI(x).FormatDescription.Equals("JPEG")) Then
                    jpegICI = arrayICI(x)
                    Exit For
                End If
            Next
            myEncoder = System.Drawing.Imaging.Encoder.Quality
            myEncoderParameters = New System.Drawing.Imaging.EncoderParameters(1)
            myEncoderParameter = New System.Drawing.Imaging.EncoderParameter(myEncoder, 60L)
            myEncoderParameters.Param(0) = myEncoderParameter
            imgFoto.Save(dest, jpegICI, myEncoderParameters)
            imgFoto.Dispose()
            imgTmp.Dispose()

        Catch ex As Exception

        End Try
End Function

- Bây giờ bạn quay lại viết cho mình nút "Save" như sau nha:

 Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        Dim tempFileName As String
        Dim svdlg As New SaveFileDialog()
        svdlg.Filter = "JPEG files (*.jpg)|*.jpg|All files (*.*)|*.*"
        svdlg.FilterIndex = 1
        svdlg.RestoreDirectory = True
        If svdlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
            tempFileName = svdlg.FileName           'check the file exist else save the cropped image
            Try
                Dim img As Image = picPreview.Image

                SavePhoto(img, tempFileName, 225)
            Catch exc As Exception
                MsgBox("Error on Saving: " & exc.Message)
            End Try
        End If
End Sub

- Thế là xong rồi đấy. Lưu ý với các thánh comment, ứng dụng mình chia sẽ đây là để học hỏi chứ ko phải viết phần mềm xử lý đồ họa như Photoshop, ACDSee, ....À bạn nào làm biếng thì có thể download demo bên dưới nha.

Download Project

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

Image Crop (Cắt ảnh đơn giản) với VB.NET
Đăng bởi: Hoàng Tử Nhỏ - Lượt xem: 16197 20:49:16, 12/11/2015VB.NET   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp