|
楼主 |
发表于 2024-8-12 00:17
|
显示全部楼层
再来个蒙版绘图
- Sub test()
- Cells.Interior.Color = xlNone '清除画布
- Application.ScreenUpdating = False '关闭屏幕显示
- Dim arrRGB(), brrRGB() '定义图片与蒙版的RGB数组
- Dim fpath1 As String, fpath2 As String
- fpath1 = ThisWorkbook.Path & "\girl2.jpg" '图片文件路径
- fpath2 = ThisWorkbook.Path & "\huazi.png" '蒙版文件路径
- '蒙版以白色作背景,非白色区为图片展示区,
- '蒙版宽和高均不大于所展示图片的宽和高
-
- arrRGB = getArrRGB(fpath1) '获取图片RGB数据
- brrRGB = getArrRGB(fpath2) '获取蒙版的RGB数据
- Dim width As Integer, height As Integer
- width = UBound(brrRGB, 2) '获取蒙版的宽
- height = UBound(brrRGB, 1) '获取蒙版的高
- For i = 1 To UBound(brrRGB, 1)
- For j = 1 To UBound(brrRGB, 2)
-
- maskR = brrRGB(i, j)(0) '获取蒙版像素R值
- maskG = brrRGB(i, j)(1) '获取蒙版像素G值
- maskB = brrRGB(i, j)(2) '获取蒙版像素B值
- picR = arrRGB(i, j)(0) '获取图片像素R值
- picG = arrRGB(i, j)(1) '获取图片像素G值
- picB = arrRGB(i, j)(2) '获取图片像素B值
-
- '在蒙版蓝色区域(B值>=250)填充对应的图片颜色
- '其它区域填充蒙版颜色
- '当然也可以更改为别的什么规则
- If maskR < 255 And maskG < 255 And maskB >= 250 Then
- Cells(i, j).Interior.Color = RGB(picR, picG, picB)
- Else
- Cells(i, j).Interior.Color = RGB(maskR, maskG, maskB)
- End If
- Next
- Next
- Application.ScreenUpdating = True
- End Sub
- Function getArrRGB(fpath As String) As Variant
- '此函数输入参数为完整的文件路径,将返回一个二维数组,
- '数组的行数为图片的高(单位:像素)
- '数组的列数为图片的宽(单位:像素)
- '数组的每一项代表一个像素点的RGB数据,
- '是一个嵌套的小数组,包含3个元素,即R、G、B值。
- Dim myImg As Object
- Set myImg = CreateObject("WIA.ImageFile")
-
- myImg.LoadFile fpath '载入图片文件
-
- Dim width As Long
- Dim height As Long
- width = myImg.width
- height = myImg.height
- Dim myVct As Object
- Set myVct = CreateObject("WIA.Vector")
- Set myVct = myImg.ARGBData '载入图片像素ARGB数据
- Dim colorARGB As String
- Dim redVal As Long, greenVal As Long, blueVal As Long
- Dim Row As Long, col As Long
- Dim arrRGB()
- ReDim arrRGB(1 To height, 1 To width)
-
- For Row = 1 To height
- For col = 1 To width
- colorARGB = Hex(myVct((Row - 1) * width + col))
- redVal = CInt("&H" & Mid(colorARGB, 3, 2))
- greenVal = CInt("&H" & Mid(colorARGB, 5, 2))
- blueVal = CInt("&H" & Mid(colorARGB, 7, 2))
- ' 确保行和列在 Excel 工作表的范围内
- If Row <= Rows.Count And col <= Columns.Count Then
- arrRGB(Row, col) = Array(redVal, greenVal, blueVal)
- End If
- Next col
- Next Row
- Set myImg = Nothing
- Set myVct = Nothing
- getArrRGB = arrRGB() '返回RGB数据的数组
- End Function
复制代码 |
|