GrayScale変換を行う(LockBitsバージョン)

概要


グレースケール変換のLockBitsバージョンです。
24bppのBitmap(sBmp)を8bppのBitmap(dBmp)に変換しています。
GetPixel/SetPixelバージョンはこちら
(事前準備や解説も、上記を参照してください。)


【ソースコード】


Option Strict On
Imports System.Drawing.Imaging

Public Class Form1
 Private sBmp As Bitmap = New Bitmap(“C:\aaa.jpg”)
 Private dBmp As Bitmap

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

  If dBmp Is Nothing Then Exit Sub
  e.Graphics.DrawImage(dBmp, 0, 0)

 End Sub

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

  dBmp = New Bitmap(sBmp.Width, sBmp.Height, PixelFormat.Format8bppIndexed)
  GrayScale(sBmp)
  PictureBox1.Invalidate()

 End Sub

 Public Sub GrayScale(ByVal srcBmp As Bitmap)

  Dim Col(255) As Color
  For i As Integer = 0 To 255
   Col(i) = Color.FromArgb(i, i, i)
  Next

  Dim pal As ColorPalette = dBmp.Palette
  For i As Integer = 0 To 255
   pal.Entries(i) = Col(i)
  Next

  dBmp.Palette = pal
  Dim bmpSr As BitmapData = sBmp.LockBits(New Rectangle(0, 0, sBmp.Width, sBmp.Height), ImageLockMode.ReadWrite, sBmp.PixelFormat)
  Dim ptrSr As IntPtr = bmpSr.Scan0
  Dim bytesSr As Integer = bmpSr.Stride * sBmp.Height
  Dim rgbvaluesSr(bytesSr) As Byte
  Dim bmpDs As BitmapData = dBmp.LockBits(New Rectangle(0, 0, dBmp.Width, dBmp.Height), ImageLockMode.ReadWrite, dBmp.PixelFormat)
  Dim ptrDs As IntPtr = bmpDs.Scan0
  Dim bytesDs As Integer = bmpDs.Stride * dBmp.Height
  Dim rgbvaluesDs(bytesDs) As Byte
  System.Runtime.InteropServices.Marshal.Copy(ptrSr, rgbvaluesSr, 0, bytesSr)
  System.Runtime.InteropServices.Marshal.Copy(ptrDs, rgbvaluesDs, 0, bytesDs)
  Dim bufCol As Color

  For i As Integer = 0 To rgbvaluesSr.Length – 3 Step 3
   bufCol = Color.FromArgb(rgbvaluesSr(i + 2), rgbvaluesSr(i + 1), rgbvaluesSr(i + 0))
   rgbvaluesDs(CInt(i / 3)) = CByte(Math.Min(bufCol.R * 0.299 + bufCol.G * 0.587 + bufCol.B * 0.114, 255))
  Next
  System.Runtime.InteropServices.Marshal.Copy(rgbvaluesSr, 0, ptrSr, bytesSr)
  System.Runtime.InteropServices.Marshal.Copy(rgbvaluesDs, 0, ptrDs, bytesDs)
  sBmp.UnlockBits(bmpSr)
  dBmp.UnlockBits(bmpDs)

 End Sub

End Class

結果も同じため省略します。


関連記事


・GrayScale変換を行う


システム開発のためのVB.NETプログラミング関係一覧に戻る


Google検索の結果


system-development
https://www.spreadi-vision.com/