• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1059
  • Last Modified:

how to convert a bmp to a gray scale bmp

I need to convert a bmp to a gray scale bmp and show it using a picbox, how can I do that?

thanks in advance
1 Solution
Put a picturebox on you form and load a picture in it. After that paste the following code and call the function from a button.

Option Explicit

Private Type BITMAP
    bmType As Long
    bmWidth As Long
    bmHeight As Long
    bmWidthBytes As Long
    bmPlanes As Integer
    bmBitsPixel As Integer
    bmBits As Long
End Type
Private Declare Function GetObject Lib "gdi32" Alias "GetObjectA" (ByVal hObject As Long, ByVal nCount As Long, lpObject As Any) As Long
Private Declare Function GetBitmapBits Lib "gdi32" (ByVal hBitmap As Long, ByVal dwCount As Long, lpBits As Any) As Long
Private Declare Function SetBitmapBits Lib "gdi32" (ByVal hBitmap As Long, ByVal dwCount As Long, lpBits As Any) As Long

Private Sub MakeGreyScale()
    Dim PicBits() As Byte, PicInfo As BITMAP
    Dim Cnt As Long, BytesPerLine As Long
    Dim iGreyScale As Long
    GetObject Picture1.Image, Len(PicInfo), PicInfo
    BytesPerLine = (PicInfo.bmWidth * 3 + 3) And &HFFFFFFFC
    ReDim PicBits(1 To BytesPerLine * PicInfo.bmHeight * 3) As Byte

    GetBitmapBits Picture1.Image, UBound(PicBits), PicBits(1)

    For Cnt = 1 To UBound(PicBits) Step 4
        iGreyScale = (0.11 * PicBits(Cnt)) + (0.59 * PicBits(Cnt + 1)) + (0.3 * PicBits(Cnt + 2))
        PicBits(Cnt) = iGreyScale
        PicBits(Cnt + 1) = iGreyScale
        PicBits(Cnt + 2) = iGreyScale
    Next Cnt

    SetBitmapBits Picture1.Image, UBound(PicBits), PicBits(1)
End Sub

Private Sub Command1_Click()
End Sub

Source : http://www.visualbasicforum.com/showthread.php?threadid=86500
Richie_SimonettiIT OperationsCommented:
'Gray color according ITU standard:
lGray = (222# * rgb.rgbRed + 707# * rgb.rgbGreen + 71# * rgb.rgbBlue) / 1000
See http://www.freevbcode.com/ShowCode.Asp?ID=4997 for motre image processing

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now