menu

Rails - Authentification (login)


Melanjutkan tutorial sebelumnya kita sudah menyiapkan database untuk keperluan login. Tutorial kali ini kita akan membuat sistem login yang akan menyimpan session pada Ruby on Rails.

Oke, langsung saja kita mulai prakteknya,

Pertama, buat terlebih dahulu route untuk loginnya dengan mengedit file routes.rb pada path config/ menjadi seperti ini,
Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  # root 'application#hello'
  get 'users' => 'users#index'

  get '' => 'home#index'

  get 'signup' => 'users#_signup'
  post 'signup' => 'users#_addUser'

  get 'login' => 'auth#index'
  post 'login' => 'auth#create'

  get 'edit/:id' => 'users#_show', as: :user
  post 'edit/:id' => 'users#_edit'

  delete 'delete/:id' => 'users#_delete'
end

Selanjutnya, buat file controller baru dengan nama auth_controller.rb pada path app/controllers/ dan ketikkan code berikut,
class AuthController < ApplicationController
 def index
 end

 def create
  @user = User.find_by_email(params[:session][:email])
  if @user && @user.authenticate(params[:session][:password])
   session[:user_id] = @user.id
   redirect_to '/'
  else
   redirect_to 'login'
  end
 end
end

Kemudian buat file view baru pada folder baru juga, dengan nama file index.html.erb pada path app/views/auth/ ketikkan code berikut,
<%= provide(:title, "Login") %>
<div class="text-center">
 <h1>Login</h1>
 <br><br>
 <div class="form-group">
  <%= form_for(:session, url: login_path) do |f| %>
     <%= f.email_field :email, :placeholder => "Email", class: 'form-input', required: true %><br>
     <%= f.password_field :password, :placeholder => "Password", class: 'form-input', required: true %><br>
   <div class="left-float">
    <%= f.submit "Login", class: "btn-submit" %>
    OR <a href="/signup">Sign Up</a>
   </div>
  <% end %>
 </div>
</div>
<br>

Setelah itu tambahkan penanda jika sudah login, dengan mengedit file application.html.erb pada path app/views/layouts/ menjadi seperti ini,
<!DOCTYPE html>
<html>
  <head>
    <title><%= yield(:title) %> | Page</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <div class="header">
     <div class="content">
      <div class="left-float">
       <a href="/" class="button-header">Home</a>
       <div class="dropdown">
        <a class="button-header dropbtn" onclick="myFunction()">Table</a>
        <div id="myDropdown" class="dropdown-content">
         <a href="/users">User</a>
         <a href="#">Link 2</a>
         <a href="#">Link 3</a>
        </div>
       </div> 
      </div>
      <div class="right-float">
       <% if current_user %>
        <a href="/" class="button-header"><%= current_user.email %></a>
       <% else %>
        <a href="/login" class="button-header">Login</a>
       <% end %>
      </div>
     </div>
    </div>
    <div class="isi">
     <%= yield %>
    </div>
    <div class="footer">
  COPYRIGHT © 2016 CODEDOCT.COM ALL RIGHTS RESERVED.
 </div>
  </body>
</html>

Terakhir, tambahkan method current_user jika user sudah login, dengan mengedit file application_controller.rb pada path app/controllers/ menjadi seperti ini,
class ApplicationController < ActionController::Base
   protect_from_forgery with: :exception
   helper_method :current_user
  def hello
  render html: "hallo, dunia"
   end

 def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
 end

 def require_user
  redirect_to '/login' unless current_user
 end
end

Penambahan method current_user ini diletakkan pada application_controller.rb karena file tersebut akan selalu dipanggil pada saat mengakses controller manapun, jadi di controller manapun kita dapat mengakses siapa yang sedang login.

Sehingga tampilan akhirnya akan tampak seperti ini,

  • Pada saat sebelum login tulisan  disudut kanan atas awalnya akan bertuliskan login dan linknya akan menuju pada halaman login,


  • Sedangkan saat sudah login tulisan disudut kanan atas akan bertuliskan email yang sedang login,



===DONE!===

Rails - Authentification (prepare database)


Kembali lagi di Ruby on Rails,

Pada tutorial sebelumnya kita sudah belajar membuat sebuah sistem CRUD (delete). Kali ini kita akan belajar yang agak sedikit rumit yaitu membuat sebuah sistem login dan logout atau biasa disebut sistem authentification.

Tutorial ini akan di sajikan dalam beberapa step karena akan sangat panjang jika hanya dipraktekkan pada satu page tutorial saja. Pada step yang pertama ini akan lebih menitik beratkan pada persiapan database login yang akan digunakan.

Oke langsung saja kita mulai tutorialnya,

Pertama, tambahkan gem bcrypt pada file Gemfile seperti ini,
source 'https://rubygems.org'

gem 'rails',        '5.0.0.1'
gem 'puma',         '3.4.0'
gem 'sass-rails',   '5.0.6'
gem 'uglifier',     '3.0.0'
#gem 'coffee-rails', '4.2.1'
gem 'jquery-rails', '4.1.1'
gem 'turbolinks',   '5.0.1'
gem 'jbuilder',     '2.4.1'

group :development, :test do
  gem 'sqlite3', '1.3.11'
  gem 'byebug',  '9.0.0', platform: :mri
end

group :development do
  gem 'web-console',           '3.1.1'
  gem 'listen',                '3.0.8'
  gem 'spring',                '1.7.2'
  gem 'spring-watcher-listen', '2.0.0'
  gem 'bcrypt',                '3.1.7'
end

group :production do
  gem 'pg', '0.18.4'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
dan jangan lupa untuk mengcompilenya dengan cara ketikkan pada terminal "bundle install"

Selanjutnya, tambahkan dua field baru yaitu email dan password_digest pada file migrate (tanggal_create_users.rb) yang terletak pada path db/migrate/ sehingga code akan tampak seperti ini,
class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
        t.string :first_name
        t.string :last_name
        t.string :nick_name
        t.text :address
        t.integer :phone
        t.string :email
        t.string :password_digest
        t.date :birth_date
        t.timestamps
    end
  end
end

Kemudian, edit pula file seeds.rb pada path db/ untuk menyesuaikan dengan file migrate yang sudah dibuat, sehingga code seedsnya akan tampak seperti ini,
User.create!([
  { first_name: "Monkey", last_name: "D Garp", nick_name: "Garp", address: "East Blue", phone: 8111, email: "monkey@mail.com", password: "password", password_confirmation: "password", birth_date: DateTime.parse("01/01/1991") },
  { first_name: "John", last_name: "Wick", nick_name: "Wick", address: "New York", phone: 8112, email: "jhon@mail.com", password: "password", password_confirmation: "password", birth_date: DateTime.parse("02/02/1992") },
  { first_name: "Dracule", last_name: "Mihawk", nick_name: "Mihawk", address: "West Blue", phone: 8113, email: "dracule@mail.com", password: "password", password_confirmation: "password", birth_date: DateTime.parse("03/03/1993") },
])

Jangan lupa tambahkan aturan penulisan password dengan menambahkan code pada file model user.rb pada path app/models/ edit menjadi seperti ini,
class User < ApplicationRecord
 has_secure_password
end

Setelah itu, buka terminal kembali, dan dan ketikkan code berikut
#roleback atau hapus database
rake db:roleback
#migrate atau create database
rake db:migrate
#seed atau isi field database
rake db:seed

Untuk mengecek databasenya ketikkan pada terminal "rails console" setelah masuk ke sqlnya ketikkan "User.all" maka akan tampil, tampilan seperti ini,


yang berarti migration dan seedernya berhasil karena bertambah dua field baru yaitu email dan password_digest.

Selanjutnya tambahkan permit baru untuk field email dan password dengan edit controller user_controller.rb pada path app/controllers/ menjadi seperti ini,
class UsersController < ApplicationController
 def index
  @users = User.all
 end

 def _signup
  @user = User.new
 end

 def _addUser 
   @user = User.new(user_params) 
   if @user.save
     redirect_to '/login' 
   else 
     redirect_to '/' 
   end 
 end

 def _show
  @user = User.find(params[:id])
 end

 def _edit
  @user = User.find(params[:id])
  if @user.update(user_params)
   redirect_to '/users' 
  else 
   redirect_to '/' 
  end 
 end

 def _delete
  @user = User.find(params[:id])
  if @user.destroy
   redirect_to '/users' 
  else 
   redirect_to '/' 
  end 
 end

 private
  def user_params
   params.require(:user).permit(:first_name, :last_name, :nick_name, :address, :phone, :email, :password)
  end
end

Kemudian edit view file index.html.erb pada path app/views/users/ menjadi seperti ini,
<%= provide(:title, "User") %>
<h1>Table user</h1>
<br>
<table border="1px" width="100%">
 <thead>
  <tr>
   <th>No</th>
   <th>Name</th>
   <th>Nick Name</th>
   <th>Address</th>
   <th>Phone number</th>
   <th>Email</th>
   <th>Birthdate</th>
   <th>Action</th>
  </tr>
 </thead>
 <tbody>
  <% no=1; @users.each do |x| %>
  <% if !x.first_name then x.first_name='' end; if !x.last_name then x.last_name='' end %>
   <tr>
    <td><%= no %></td>
    <td><%= x.first_name+' '+x.last_name %></td>
    <td><%= x.nick_name %></td>
    <td><%= x.address %></td>
    <td><%= x.phone %></td>
    <td><%= x.email %></td>
    <td><%= x.birth_date %></td>
    <td><%= link_to "Edit", user_path(x) %> || <%= link_to 'Delete',  { action: :_delete, id: x.id }, method: :delete, data: { confirm: 'Are you sure?' } %></td>
   </tr>
  <% no+=1; end %>
 </tbody>
</table>

Setelah itu edit pula view _signup.html.erb pada path app/views/users/ menjadi seperti ini,
<%= provide(:title, "Sign Up") %>
<div class="text-center">
 <h1>Sign up</h1>
 <br><br>
 <div class="form-group">
  <%= form_for(@user, url: {action: "_addUser"}, method: "post") do |f| %>
     <%= f.text_field :first_name, :placeholder => "First name", class: 'form-input', required: true %><br>
     <%= f.text_field :last_name, :placeholder => "Last name", class: 'form-input', required: true %><br>
     <%= f.text_field :nick_name, :placeholder => "Nick name", class: 'form-input', required: true %><br>
     <%= f.text_area :address, :placeholder => "Address", class: 'form-input-textarea', required: true %><br>
     <%= f.number_field :phone, :placeholder => "Phone number", class: 'form-input', required: true %><br>
     <%= f.email_field :email, :placeholder => "Email", class: 'form-input', required: true %><br>
     <%= f.password_field :password, :placeholder => "Password", class: 'form-input', required: true %><br>
   <div class="left-float">
    <%= f.submit "Create an account", class: "btn-submit" %>
   </div>
     <div class="right-float">
      <!--input type="button" name="login" value="Login" class="btn-submit"-->
   </div>
  <% end %>
 </div>
</div>
<br>

Terakhir edit view _show.html.erb pada path app/views/users/ menjadi seperti ini,
<%= provide(:title, "Edit") %>
<h1>Edit User</h1>
<br>
<div class="form-group">
 <%= form_for(@user, url: {action: "_edit"}, method: "post") do |f| %>
  <label>First Name</label>
    <%= f.text_field :first_name, :value => @user.first_name, class: 'form-input', required: true %><br>
    <label>Last Name</label>
    <%= f.text_field :last_name, :value => @user.last_name, class: 'form-input', required: true %><br>
    <label>Nick Name</label>
    <%= f.text_field :nick_name, :value => @user.nick_name, class: 'form-input', required: true %><br>
    <label>Address</label>
    <%= f.text_area :address, :value => @user.address, class: 'form-input-textarea', required: true %><br>
    <label>Phone</label>
    <%= f.number_field :phone, :value => @user.phone, class: 'form-input', required: true %><br>
    <%= f.email_field :email, :value => @user.email, class: 'form-input', required: true %><br>
    <%= f.password_field :password, :value => @user.password, class: 'form-input', required: true %><br>
  <%= f.submit "Save", class: "btn-submit" %>  <input type="button" onclick="location.href='/users';" value="Cancel" class="btn-submit" />
 <% end %>
</div>

Sehingga salah satu tampilan viewnya akan berubah seperti ini,


===DONE!===

Visual Basic - Image Processing 6 (convert)


Hello everyone, akhirnya sampai juga kita pada tutorial terakhir dari bab image processing ini, selanjutnya akan dijelaskan lebih lanjut tentang Jaringan Saraf Tiruan.

Pada tutorial kali ini, kita akan membuat sebuah engine yang mampu mengconvert format suatu image menjadi format yang lain,

Tutorial kali ini merupakan lanjutan tutorial sebelumnya tentang Edge Detection, jika belum paham tentang Visual Basic baca disini.

Oke langsung saja kita mulai tutorialnya,

Pertama, buat sebuah User Interface menggunakan tools PictureBox, ComboBox, Button, OpenFileDialog, dan SaveFileDialog sehingga hasilnya akan tampak seperti ini,


Untuk membuat ComboBox, tambahkan itemsnya pada items (collection) dan tampilannya akan tampak seperti ini,


Selanjutnya klik 2x Button Select dan ketikkan code berikut,
OpenFileDialog1.Title = "Masukkan Gambar"
OpenFileDialog1.Filter = "image file (*.jpg) |*.jpg| image file (*.psd) |*.psd| image file (*.png) |*.png| image file (*.gif) |*.gif| image file (*.bmp) |*.bmp| all files (*.*) | *.*"
OpenFileDialog1.FileName = ""
If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
    PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If

Kemudian klik 2x Button Convert dan ketikkan code berikut,
        If ComboBox1.SelectedItem = "JPEG" Then
            Try
                SaveFileDialog1.Filter = "JPEG |*.jpeg"
                If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    PictureBox1.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
                End If
            Catch ex As Exception
            End Try
        End If
        If ComboBox1.SelectedItem = "PSD" Then
            Try
                SaveFileDialog1.Filter = "PSD |*.psd"
                If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    PictureBox1.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
                End If
            Catch ex As Exception
            End Try
        End If
        If ComboBox1.SelectedItem = "PNG" Then
            Try
                SaveFileDialog1.Filter = "PNG |*.png"
                If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    PictureBox1.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
                End If
            Catch ex As Exception
            End Try
        End If
        If ComboBox1.SelectedItem = "GIF" Then
            Try
                SaveFileDialog1.Filter = "GIF |*.gif"
                If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    PictureBox1.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
                End If
            Catch ex As Exception
            End Try
        End If
        If ComboBox1.SelectedItem = "BMP" Then
            Try
                SaveFileDialog1.Filter = "BMP |*.bmp"
                If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    PictureBox1.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
                End If
            Catch ex As Exception
            End Try
        End If
        MsgBox("Success")

Sehingga fullcodenya akan tampak seperti ini,
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        OpenFileDialog1.Title = "Masukkan Gambar"
        OpenFileDialog1.Filter = "image file (*.jpg) |*.jpg| image file (*.psd) |*.psd| image file (*.png) |*.png| image file (*.gif) |*.gif| image file (*.bmp) |*.bmp| all files (*.*) | *.*"
        OpenFileDialog1.FileName = ""
        If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
            PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If ComboBox1.SelectedItem = "JPEG" Then
            Try
                SaveFileDialog1.Filter = "JPEG |*.jpeg"
                If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    PictureBox1.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
                End If
            Catch ex As Exception
            End Try
        End If
        If ComboBox1.SelectedItem = "PSD" Then
            Try
                SaveFileDialog1.Filter = "PSD |*.psd"
                If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    PictureBox1.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
                End If
            Catch ex As Exception
            End Try
        End If
        If ComboBox1.SelectedItem = "PNG" Then
            Try
                SaveFileDialog1.Filter = "PNG |*.png"
                If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    PictureBox1.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
                End If
            Catch ex As Exception
            End Try
        End If
        If ComboBox1.SelectedItem = "GIF" Then
            Try
                SaveFileDialog1.Filter = "GIF |*.gif"
                If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    PictureBox1.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
                End If
            Catch ex As Exception
            End Try
        End If
        If ComboBox1.SelectedItem = "BMP" Then
            Try
                SaveFileDialog1.Filter = "BMP |*.bmp"
                If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    PictureBox1.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
                End If
            Catch ex As Exception
            End Try
        End If
        MsgBox("Success")
    End Sub

    Private Sub Form1_load(sender As Object, e As EventArgs) Handles MyBase.Load
        ComboBox1.SelectedItem = "JPEG"
    End Sub
End Class

Dan tampilan akhirnya akan tampak seperti ini,



===DONE!===

Visual Basic - Image Processing 5 (edge detection)


Lanjut lagi image processing,,

Pada tutorial sebelumnya kita sudah sampai pada membuat sebuah engine yang mampu meng-greyscale image, tutorial kali ini kita akan membuat sebuah engine kembali yang mampu mendeteksi garis tepi suatu citra atau bisa disebut sebagai Edge Detection,

Belum begitu mengerti tentang Visual Studion? bisa lihat disini,
Oke langsung saja kita mulai prakteknya,,

Pertama buat dulu User Interfacenya menggunakan, GroupBox, PictureBox, OpenFileDialog, SaveFileDialog, dan Button, sehingga hasilnya akan tampak seperti ini,


Selanjutnya klik 2x Button Open dan ketikkan code berikut,
OpenFileDialog1.Filter = "Images|*.GIF; *.TIF;*.JPG;*BMP"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName = "" Then Exit Sub
PicAda = True
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
PictureBox2.Image = Image.FromFile(OpenFileDialog1.FileName)

Kemudian klik 2x Button Process dan ketikkan code berikut,
If PicAda = False Then
     MsgBox("Pilih dulu gambar yang akan diproses", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Proses gagal")
     Exit Sub
End If
Dim source As New Bitmap(PictureBox1.Image)
Dim sobelResult As New Bitmap(PictureBox1.Image)

Dim sobelX, sobelY, magnitude As Integer

Dim neighbourList As ArrayList = New ArrayList
Call Greyscale()
For y As Integer = 0 To source.Height - 1
     For x As Integer = 0 To source.Width - 1
         neighbourList.Clear()

         neighbourList = getThreeNeighbourList(x, y, source)

         sobelX = getSobelValue(neighbourList, "X")
         sobelY = getSobelValue(neighbourList, "Y")

         magnitude = Math.Sqrt(Math.Pow(sobelX, 2) + Math.Pow(sobelY, 2))

         If magnitude > 150 Then
             magnitude = 255
         Else
             magnitude = 0
         End If

         sobelResult.SetPixel(x, y, Color.FromArgb(magnitude, magnitude, magnitude))
     Next x
Next y

PictureBox2.Image = sobelResult
MessageBox.Show("Proses Sobel Telah Selesai")

Setelah itu klik 2x Button Save dan ketikkan code berikut,
Try
    SaveFileDialog1.Filter = "JPEG |*.jpg"
    If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
        PictureBox2.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
    End If
Catch ex As Exception
End Try

Terakhir ketikkan code edge detection berikut,
     Public Function getSobelValue(ByVal neighbourList As ArrayList, ByVal maskType As String) As Integer
        Dim result As Integer = 0

        Dim sobelX As Integer(,) = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}}
        Dim sobelY As Integer(,) = {{1, 2, 1}, {0, 0, 0}, {-1, -2, -1}}

        Dim count As Integer = 0

        If (maskType.Equals("X")) Then
            For y As Integer = 0 To 2
                For x As Integer = 0 To 2
                    result = result + (sobelX(x, y) * Convert.ToInt16(neighbourList(count)))

                    count = count + 1
                Next x
            Next y
        ElseIf (maskType.Equals("Y")) Then
            For y As Integer = 0 To 2
                For x As Integer = 0 To 2
                    result = result + (sobelY(x, y) * Convert.ToInt16(neighbourList(count)))

                    count = count + 1
                Next x
            Next y
        End If

        Return result
    End Function

    Public Function getThreeNeighbourList(ByVal xPos As Integer, ByVal yPos As Integer, ByVal source As Bitmap) As ArrayList
        Dim neighbourList As ArrayList = New ArrayList

        Dim xStart, xFinish, yStart, yFinish As Integer

        Dim pixel As Integer

        xStart = xPos - 1
        xFinish = xPos + 1

        yStart = yPos - 1
        yFinish = yPos + 1

        For y As Integer = yStart To yFinish
            For x As Integer = xStart To xFinish
                If (x < 0) Or (y < 0) Or (x > source.Width - 1) Or (y > source.Height - 1) Then
                    neighbourList.Add(0)
                Else
                    pixel = source.GetPixel(x, y).R

                    neighbourList.Add(pixel)
                End If
            Next x
        Next y

        Return neighbourList
    End Function
    Private Sub Greyscale()
        Dim source As New Bitmap(PictureBox1.Image)

        Dim red, green, blue, grayscale As Integer

        For y As Integer = 0 To source.Height - 1
            For x As Integer = 0 To source.Width - 1
                red = source.GetPixel(x, y).R
                green = source.GetPixel(x, y).G
                blue = source.GetPixel(x, y).B

                grayscale = red * 0.299 + green * 0.587 + blue * 0.114

                source.SetPixel(x, y, Color.FromArgb(grayscale, grayscale, grayscale))
            Next x
        Next y

        PictureBox1.Image = source
    End Sub

Sehingga full codenya akan tampak seperti ini,
Public Class Form1
    Dim PicAda As Boolean
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        OpenFileDialog1.Filter = "Images|*.GIF; *.TIF;*.JPG;*BMP"
        OpenFileDialog1.ShowDialog()
        If OpenFileDialog1.FileName = "" Then Exit Sub
        PicAda = True
        PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
        PictureBox2.Image = Image.FromFile(OpenFileDialog1.FileName)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If PicAda = False Then
            MsgBox("Pilih dulu gambar yang akan diproses", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Proses gagal")
            Exit Sub
        End If
        Dim source As New Bitmap(PictureBox1.Image)
        Dim sobelResult As New Bitmap(PictureBox1.Image)

        Dim sobelX, sobelY, magnitude As Integer

        Dim neighbourList As ArrayList = New ArrayList
        Call Greyscale()
        For y As Integer = 0 To source.Height - 1
            For x As Integer = 0 To source.Width - 1
                neighbourList.Clear()

                neighbourList = getThreeNeighbourList(x, y, source)

                sobelX = getSobelValue(neighbourList, "X")
                sobelY = getSobelValue(neighbourList, "Y")

                magnitude = Math.Sqrt(Math.Pow(sobelX, 2) + Math.Pow(sobelY, 2))

                If magnitude > 150 Then
                    magnitude = 255
                Else
                    magnitude = 0
                End If

                sobelResult.SetPixel(x, y, Color.FromArgb(magnitude, magnitude, magnitude))
            Next x
        Next y

        PictureBox2.Image = sobelResult
        MessageBox.Show("Proses Sobel Telah Selesai")
    End Sub

    Public Function getSobelValue(ByVal neighbourList As ArrayList, ByVal maskType As String) As Integer
        Dim result As Integer = 0

        Dim sobelX As Integer(,) = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}}
        Dim sobelY As Integer(,) = {{1, 2, 1}, {0, 0, 0}, {-1, -2, -1}}

        Dim count As Integer = 0

        If (maskType.Equals("X")) Then
            For y As Integer = 0 To 2
                For x As Integer = 0 To 2
                    result = result + (sobelX(x, y) * Convert.ToInt16(neighbourList(count)))

                    count = count + 1
                Next x
            Next y
        ElseIf (maskType.Equals("Y")) Then
            For y As Integer = 0 To 2
                For x As Integer = 0 To 2
                    result = result + (sobelY(x, y) * Convert.ToInt16(neighbourList(count)))

                    count = count + 1
                Next x
            Next y
        End If

        Return result
    End Function

    Public Function getThreeNeighbourList(ByVal xPos As Integer, ByVal yPos As Integer, ByVal source As Bitmap) As ArrayList
        Dim neighbourList As ArrayList = New ArrayList

        Dim xStart, xFinish, yStart, yFinish As Integer

        Dim pixel As Integer

        xStart = xPos - 1
        xFinish = xPos + 1

        yStart = yPos - 1
        yFinish = yPos + 1

        For y As Integer = yStart To yFinish
            For x As Integer = xStart To xFinish
                If (x < 0) Or (y < 0) Or (x > source.Width - 1) Or (y > source.Height - 1) Then
                    neighbourList.Add(0)
                Else
                    pixel = source.GetPixel(x, y).R

                    neighbourList.Add(pixel)
                End If
            Next x
        Next y

        Return neighbourList
    End Function
    Private Sub Greyscale()
        Dim source As New Bitmap(PictureBox1.Image)

        Dim red, green, blue, grayscale As Integer

        For y As Integer = 0 To source.Height - 1
            For x As Integer = 0 To source.Width - 1
                red = source.GetPixel(x, y).R
                green = source.GetPixel(x, y).G
                blue = source.GetPixel(x, y).B

                grayscale = red * 0.299 + green * 0.587 + blue * 0.114

                source.SetPixel(x, y, Color.FromArgb(grayscale, grayscale, grayscale))
            Next x
        Next y

        PictureBox1.Image = source
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Try
            SaveFileDialog1.Filter = "JPEG |*.jpg"
            If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                PictureBox2.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
            End If
        Catch ex As Exception
        End Try
    End Sub
End Class

Dan tampilan akhirnya akan tampak seperti ini,



===DONE!===

Visual Basic - Image Processing 4 (greyscale)


Setelah seminggu tidak menulis karena sakit, akhirnya diberi kesempatan kembali untuk menulis lagi, oke pada tutorial sebelumnya kita sudah membuat salah satu sistem dari image processing yaitu cropping, kali ini kita akan membuat sistem greyscale.

Greyscale sendiri adalah warna-warna piksel yang hanya terdiri dari warna hitam dan putih saja.

Belum terlalu mengerti tentang Visual Studio? baca disini, oke langsung saja kita buat enginenya.

Pertama, buat UI (User Interface) pada visual basic menggunakan tools OpenFileDialog, SaveFileDialog, Button, dan PictureBox sehingga tampilannya akan tampak seperti ini,


Selanjutnya, klik dua kali button Open dan ketikkan code berikut,
        OpenFileDialog1.Filter = "image file (*.jpg) |*.jpg| all files (*.*) | *.*"
        If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
            PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
        End If

Kemudian, klik dua kali button Process dan ketikkan code berikut,
PictureBox1.Image = gray(PictureBox1.Image)

Terakhir, klik dua kali button Save dan ketikkan code berikut,
        Try
            SaveFileDialog1.Filter = "JPEG |*.jpeg"
            If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                PictureBox1.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
            End If
        Catch ex As Exception
        End Try

Tambahkan Import dan juga function grey, sehingga fullcodenya akan tampak seperti ini
Imports System.Drawing.Imaging
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        OpenFileDialog1.Filter = "image file (*.jpg) |*.jpg| all files (*.*) | *.*"
        If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
            PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        PictureBox1.Image = gray(PictureBox1.Image)
    End Sub

    Public Function gray(ByVal image As Bitmap) As Bitmap
        Dim a As New Bitmap(image.Width, image.Height)
        Dim b As Graphics = Graphics.FromImage(a)
        Dim c As New ColorMatrix(New Single()() {New Single() {0.3F, 0.3F, 0.3F, 0, 0},
                                                 New Single() {0.59F, 0.59F, 0.59F, 0, 0},
                                                 New Single() {0.11F, 0.11F, 0.11F, 0, 0},
                                                 New Single() {0, 0, 0, 1, 0},
                                                 New Single() {0, 0, 0, 0, 1}})
        Dim d As New ImageAttributes()
        d.SetColorMatrix(c)
        b.DrawImage(image, New Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, d)
        d.Dispose()
        Return a
    End Function

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Try
            SaveFileDialog1.Filter = "JPEG |*.jpeg"
            If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                PictureBox1.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
            End If
        Catch ex As Exception
        End Try
    End Sub
End Class

Dan tampilannya akan tampak seperti ini,


===DONE!===

Visual Basic - Image Processing 3 (cropping)


Tutorial kemarin kita sudah membuat sebuah program yang dapat membaca nilai atau value RGB dan mengkoversinya menjadi sebuah image. Pada tutorial kali ini kita akan membuat sebuah program cropping atau pemotongan gambar.

Baru belajar Visual Basic? pahami artikel ini dulu,
Oke, langsung saja kita mulai tutorialnya,

Pertama, buat UI (User Interface) pada visual basic menggunakan tools OpenFileDialog dan SaveFileDialog  sehingga tampilannya akan tampak seperti ini,


Selanjutnya klik2 kali form UI-nya kemudian ketikkan codenya sehingga akan tampak seperti ini,
Public Class Form1
    Dim selection As Rectangle
    Dim down As Boolean
    Dim filedialog As New OpenFileDialog
    Dim imagebitmap As Bitmap
    Dim selectioncolour As Color = Color.Black
    Dim bordersize As Integer = 2

    Function changealpha(ByVal colour As Color, ByVal value As Integer) As Color
        Dim c As Color
        c = (Color.FromArgb((value), (colour)))
        Return (c)
    End Function
    Function cropimage(ByVal image As Bitmap) As Bitmap
        Dim cropped As Bitmap = image.Clone(selection, image.PixelFormat)
        Return cropped
    End Function

    Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
        Select Case e.KeyCode
            Case Keys.O
                If Not filedialog.ShowDialog = Windows.Forms.DialogResult.Cancel Then imagebitmap = New Bitmap(filedialog.FileName)
                Me.BackgroundImage = imagebitmap
                Me.BackgroundImageLayout = ImageLayout.None
                Me.Invalidate()
            Case Keys.C
                'cropimage(imagebitmap).Save("C:\Data\")
                Try
                    SaveFileDialog1.Filter = "JPEG |*.jpeg"
                    If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                        cropimage(imagebitmap).Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
                    End If
                Catch ex As Exception
                End Try
            Case Keys.Space
                selection = New Rectangle(New Point(selection.X, selection.Y), New Size(InputBox("width", "", selection.Width), InputBox("height", "", selection.Height)))
                Me.Invalidate()
        End Select
    End Sub


    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True)
        Me.SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
        selection = New Rectangle(New Point(0, 0), New Size(100, 100))
        Me.Invalidate()
    End Sub
    Private Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown
        down = True
    End Sub

    Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
        If down = True Then
            selection = New Rectangle(e.Location, selection.Size)
            Me.Invalidate()
        End If
    End Sub

    Private Sub Form1_MouseUp(sender As Object, e As MouseEventArgs) Handles Me.MouseUp
        down = False
    End Sub

    Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
        e.Graphics.FillRectangle((New SolidBrush((changealpha((selectioncolour), 100)))), selection)
        e.Graphics.DrawRectangle((New Pen((New SolidBrush((selectioncolour))), bordersize)), selection)
        e.Graphics.DrawString(selection.Width & "x" & selection.Height, New Font("arial", 10, FontStyle.Regular), Brushes.White, selection.X, selection.Y)
    End Sub
End Class

Sehingga tampilannya akan tampak seperti ini,


Untuk menggunakannya:
o     : Open file
c     : Crop+save
space : Ubah ukuran crop
mouse : Untuk memindahkan kotak cropping

===DONE!===

Visual Basic - Image Processing 2 (make image from RGB)


Pada tutorial kemarin kita sudah membuat sebuah engine untuk membaca nilai RGB dari suatu Image, sebaliknya tutorial kali ini kita akan membuat sebuah engine yang dapat mengkoversi nilai RGB menjadi sebuah image.

Sebelum memulai tutorial kali ini, ada baiknya pahami terlebih dahulu tutorial sebelumnya.

Oke, jika anda sudah memahami tutorial sebelumnya, saatnya kita memulai prakteknya,

Pertama, buat design UI-nya dengan menggunakan tools richtextbox, button, picturebox, dan groupbox kira-kira tampilannya seperti ini,


Kemudian, klik 2kali button Make image dan ketikkan code berikut,
        Button1.Text = "waiting"
        Button1.Enabled = False

        CheckForIllegalCrossThreadCalls = False

        Dim width As Integer = CInt(TextBox1.Text.Split(CChar("|"))(1).Split(CChar("*"))(0))
        Dim height As Integer = CInt(TextBox1.Text.Split(CChar("|"))(1).Split(CChar("*"))(1))
        bild = New Bitmap(width, height)

        TextBox1.Text = TextBox1.Text.Split(CChar("|"))(0)

        For Each line In TextBox1.Lines

            Dim farbe As String = line.Split(CChar("'"))(0)
            Dim R, G, B, A As Integer
            Dim geteilt() As String = farbe.Split(CChar("-"))

            R = CInt(geteilt(0))
            G = CInt(geteilt(1))
            B = CInt(geteilt(2))
            A = CInt(geteilt(3))

            Dim x As Integer = CInt(CDbl(line.Split(CChar("'"))(1).Split(CChar(","))(0)))
            Dim y As Integer = CInt(CDbl(line.Split(CChar("'"))(1).Split(CChar(","))(1)))

            Dim c As Color = Color.FromArgb(A, R, G, B)
            bild.SetPixel(CInt(x) - 1, CInt(y) - 1, c)
        Next
        PictureBox1.Image = bild
        Button1.Text = "Done"
        Button1.Enabled = True

Selanjutnya tambahkan code berikut untuk mendeklarasikan bild sebagai sebuah object bitmap,
Dim bild As Bitmap

Sehingga fullcodenya akan tampak seperti ini,
Public Class Form1
    Dim bild As Bitmap
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Button1.Text = "waiting"
        Button1.Enabled = False

        CheckForIllegalCrossThreadCalls = False

        Dim width As Integer = CInt(TextBox1.Text.Split(CChar("|"))(1).Split(CChar("*"))(0))
        Dim height As Integer = CInt(TextBox1.Text.Split(CChar("|"))(1).Split(CChar("*"))(1))
        bild = New Bitmap(width, height)

        TextBox1.Text = TextBox1.Text.Split(CChar("|"))(0)

        For Each line In TextBox1.Lines

            Dim farbe As String = line.Split(CChar("'"))(0)
            Dim R, G, B, A As Integer
            Dim geteilt() As String = farbe.Split(CChar("-"))

            R = CInt(geteilt(0))
            G = CInt(geteilt(1))
            B = CInt(geteilt(2))
            A = CInt(geteilt(3))

            Dim x As Integer = CInt(CDbl(line.Split(CChar("'"))(1).Split(CChar(","))(0)))
            Dim y As Integer = CInt(CDbl(line.Split(CChar("'"))(1).Split(CChar(","))(1)))

            Dim c As Color = Color.FromArgb(A, R, G, B)
            bild.SetPixel(CInt(x) - 1, CInt(y) - 1, c)
        Next
        PictureBox1.Image = bild
        Button1.Text = "Done"
        Button1.Enabled = True
    End Sub
End Class

Dan tampilan akhirnya akan tampak seperti ini,



Untuk test, coba silahkan masukkan nilai RGB ini pada view richtextbox-nya,
download disini,

===DONE!===

Visual Basic - Image Processing (read image)


Hello everyone, welcome back,,

Pada tutorial sebelumya kita sudah membahas tentang sistem CRUD pada Visual Basic, tutorial kali ini kita akan memulai sebuah project yang bisa dianggap sebagai project yang sangat spektakuler, dan manghabiskan waktu yang cukup lama bagi codedoct untuk melakukan research pada project ini.

Project yang akan segera dibahas codedoct kali ini adalah Image Processing (Pengolahan Citra) dan Artificial Neural Network(Jaringan Saraf Tiruan).

Jika sama sekali belum mengenal tentang Visual Basic diharapkan untuk memahaminya terlebih dahulu disini.

Oke untuk tutorial yang pertama adalah bagaimana caranya membuat sebuah software atau engine yang mampu membaca nilai RGB (Red Green Blue) dari sebuah citra Image atau gambar menggunakan Visual Basic,

Pertama buat sebuah UI yang terdiri dari picturebox, openfiledialog, textbox, label, dan richtextbox seperti ini,


Kemudian, klik 2 kali button Load Image dan masukkan code berikut, 
OpenFileDialog1.Filter = "image file (*.jpg) |*.jpg| all files (*.*) | *.*"
If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
  PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If

Selanjutnya klik 2 kali button Read Image dan ketikkan code berikut,
Button2.Text = "Please Wait..."
        Button2.Enabled = False

        CheckForIllegalCrossThreadCalls = False
        Dim bild As Bitmap = CType(Me.PictureBox1.Image.Clone, Bitmap)
        Dim width As Integer = bild.Width - 1
        Dim height As Integer = bild.Height - 1
        Dim h, i, j As Integer

        For x = 1 To width
            For y = 1 To height

                Dim R, G, B, A As Integer
                R = bild.GetPixel(x, y).R
                G = bild.GetPixel(x, y).G
                B = bild.GetPixel(x, y).B
                A = bild.GetPixel(x, y).A
                h = h + R
                i = i + G
                j = j + B

                RichTextBox1.AppendText(R & "-" & G & "-" & B & "-" & A & "'" & x & "," & y & vbNewLine)
            Next
        Next
        RichTextBox1.Text = RichTextBox1.Text.Substring(0, RichTextBox1.Text.Length - 1)
        RichTextBox1.AppendText("|" & width & "*" & height)
        hasil1.Text = h / 1000
        hasil2.Text = i / 1000
        hasil3.Text = j / 1000

        Button2.Text = "Load Data"
        Button2.Enabled = True

Sehingga full codenya akan tampak seperti ini,
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        OpenFileDialog1.Filter = "image file (*.jpg) |*.jpg| all files (*.*) | *.*"
        If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
            PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Button2.Text = "Please Wait..."
        Button2.Enabled = False

        CheckForIllegalCrossThreadCalls = False
        Dim bild As Bitmap = CType(Me.PictureBox1.Image.Clone, Bitmap)
        Dim width As Integer = bild.Width - 1
        Dim height As Integer = bild.Height - 1
        Dim h, i, j As Integer

        For x = 1 To width
            For y = 1 To height

                Dim R, G, B, A As Integer
                R = bild.GetPixel(x, y).R
                G = bild.GetPixel(x, y).G
                B = bild.GetPixel(x, y).B
                A = bild.GetPixel(x, y).A
                h = h + R
                i = i + G
                j = j + B

                RichTextBox1.AppendText(R & "-" & G & "-" & B & "-" & A & "'" & x & "," & y & vbNewLine)
            Next
        Next
        RichTextBox1.Text = RichTextBox1.Text.Substring(0, RichTextBox1.Text.Length - 1)
        RichTextBox1.AppendText("|" & width & "*" & height)
        hasil1.Text = h / 1000
        hasil2.Text = i / 1000
        hasil3.Text = j / 1000

        Button2.Text = "Load Data"
        Button2.Enabled = True
    End Sub
End Class

Dan tampilannya akan tampak seperti ini,


Masing - masing nilai RGB yang didapat adalah total dari nilai RGB setiap pixel,

===DONE!===