'因某需求,需要將圖形存成單色圖已減少硬碟空間的浪費
'相信也有人會有這樣的需求,所以就公開了,
'(腦筋動得快的應該可以猜到是「列印預覽」)
Option Explicit
Private Type BitMapFileHeader '14 bytes
bfType As Integer
bfSize As Long
bfReserved1 As Integer
bfReserved2 As Integer
bfOffBits As Long
End Type
Private Type BitMapInfoHheder '40 bytes
biSize As Long
biWidth As Long
biHeight As Long
biPlanes As Integer
biBitCount As Integer
biCompression As Long
biSizeImage As Long
biXPelsPerMeter As Long
biYPelsPerMeter As Long
biClrUsed As Long
biClrImportant As Long
End Type
Private Type RGBQuad
rgbBlue As Byte
rgbGreen As Byte
rgbRed As Byte
rgbReserved As Byte
End Type
Private Type BitMapInfo_1
bmiHeader As BitMapInfoHeader
bmiColors(1) As RGBQuad
End Type
Private Const PIXEL As Integer = 3
Private Const DIB_RGB_COLORS As Long = 0
Private Const PALVERSION = &H300
Private Declare Function GetDIBits1 Lib "gdi32" Alias "GetDIBits" _
(ByVal aHDC As Long, _
ByVal hBitmap As Long, _
ByVal nStartScan As Long, _
ByVal nNumScans As Long, _
lpBits As Any, _
lpBI As BITMAPINFO_1, _
ByVal wUsage As Long) As Long
Public Sub SaveMonoBMP(pic As PictureBox, FileName As String)
Dim SaveBitmapInfo_1 As BITMAPINFO_1
Dim SaveFileHeader As BITMAPFILEHEADER
Dim SaveBits() As Byte
Dim BufferSize As Long
Dim fNum As Long
Dim RetVal As Long
Dim nLen As Long
Dim ScaleMode As Integer
Const BitsPixel = 1
ScaleMode = pic.ScaleMode
pic.ScaleMode = 3 '切換到畫素以計算所需空間
BufferSize = ((pic.ScaleWidth / 8 + 3) And &HFFFC) * pic.ScaleHeight
ReDim SaveBits(BufferSize - 1)
With SaveBitmapInfo_1.bmiHeader
.biSize = 40
.biWidth = pic.ScaleWidth
.biHeight = pic.ScaleHeight
.biPlanes = 1
.biBitCount = BitsPixel
.biCompression = 0
.biClrUsed = 0
.biClrImportant = 0
.biSizeImage = BufferSize
End With
nLen = Len(SaveBitmapInfo_1)
RetVal = GetDIBits1(pic.hDC, _
pic.Image, _
0, _
SaveBitmapInfo_1.bmiHeader.biHeight, _
SaveBits(0), _
SaveBitmapInfo_1, _
DIB_RGB_COLORS)
With SaveFileHeader
.bfType = &H4D42
.bfSize = Len(SaveFileHeader) + nLen + BufferSize
.bfOffBits = Len(SaveFileHeader) + nLen
End With
fNum = FreeFile
Open FileName For Binary As fNum
Put fNum, , SaveFileHeader
Put fNum, , SaveBitmapInfo_1
Put fNum, , SaveBits()
Close fNum
pic.ScaleMode = ScaleMode
End Sub