|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
分享另外一种方法,仅支持BMP位图
- Sub BMP2excelPixel()
- Dim Filename As Variant
- MsgBox "仅支持BMP格式图片,因Excel格式限制,建议像素控制在400*400以内。"
- Filename = Application.GetOpenFilename("BMP图片,*.bmp", , "请选择BMP图片", , 0)
-
- If Filename = False Then
- Exit Sub
- End If
- Dim bmpFilePath As String
- bmpFilePath = CStr(Filename)
- Dim arrByte() As Byte
- Dim PixelCol As LongPtr, PixelRow As LongPtr
- Dim CellCol As LongPtr, CellRow As LongPtr
- Dim i As Long, j As Long
- Dim lngPos As LongPtr, Zeroize As LongPtr
-
- '获取BMP图片信息并放入二进制数组,BMP文件格式存放像素的方法:一个像素由3个字节来完成:从下到上,从左到右,BGRBGR的顺序
- Open bmpFilePath For Binary As #1
- ReDim arrByte(LOF(1) - 1)
- 'ReDim arrByte(2 ^ 31 - 1)
- Get #1, , arrByte
- Close #1
-
- '获取图片的像素高和宽。BMP文件格式第18-21位为256进制像素宽度,22-25位为256进制像素高度,因Windows系统一个扫描行所占的字节数必须是4的倍数,宽度不是4的倍数时需补零
- For i = 0 To 3
- PixelCol = PixelCol + arrByte(i + 18) * 256 ^ i
- Next
- For i = 0 To 3
- PixelRow = PixelRow + arrByte(i + 22) * 256 ^ i
- Next
- If PixelCol Mod 4 <> 0 Then Zeroize = PixelCol Mod 4
-
- Cells.Clear
- Range(Cells(1, 1), Cells(PixelRow, PixelCol)).Select
- Selection.RowHeight = 3
- Selection.ColumnWidth = 0.31
-
- 'BMP文件格式存放像素的方法:一个像素由3个字节来完成:从下到上,从左到右,BGRBGR的顺序
- For i = PixelRow To 1 Step -1
- CellRow = CellRow + 1
- CellCol = 0
- For j = 1 To PixelCol * 3 Step 3
- CellCol = CellCol + 1
- lngPos = 53 + j + (i - 1) * (PixelCol * 3 + Zeroize)
- Cells(CellRow, CellCol).Interior.Color = RGB(arrByte(lngPos + 2), arrByte(lngPos + 1), arrByte(lngPos))
- Next
- Next
- ActiveWindow.Zoom = True
- End Sub
复制代码 |
|