用VBA写一个给目录下所有图片增加水印,水印内容自己修改,水印居中
时间: 2024-02-17 15:01:58 浏览: 111
好的,以下是一个用 VBA 给目录下所有图片增加自定义水印并居中的代码:
```vb
Sub AddWatermarkToImages()
Dim path As String
Dim file As String
Dim pic As Picture
Dim watermark As Shape
Dim picWidth As Double
Dim picHeight As Double
Dim watermarkWidth As Double
Dim watermarkHeight As Double
Dim watermarkText As String
' 设置水印文本及格式
watermarkText = "My Watermark" ' 修改为你的水印文本
Set watermark = ActiveSheet.Shapes.AddTextEffect(msoTextEffect1, watermarkText, "Arial", 48, msoFalse, msoFalse, 0, 0)
watermark.Line.Visible = msoFalse
watermark.Fill.Visible = msoTrue
watermark.Fill.ForeColor.RGB = RGB(192, 192, 192)
watermark.Fill.Transparency = 0.5
' 循环处理目录下所有图片
path = "C:\Images\" ' 修改为你的图片目录
file = Dir(path & "*.jpg") ' 修改为你的图片格式
Do While Len(file) > 0
Set pic = LoadPicture(path & file)
picWidth = pic.Width
picHeight = pic.Height
watermarkWidth = watermark.Width
watermarkHeight = watermark.Height
' 将水印居中
watermark.Left = (picWidth - watermarkWidth) / 2
watermark.Top = (picHeight - watermarkHeight) / 2
' 给图片增加水印并保存
With ActiveSheet.Shapes.AddPicture(pic, msoFalse, msoTrue, 0, 0, picWidth, picHeight)
.ZOrder msoSendToBack
.Fill.Visible = msoFalse
.Line.Visible = msoFalse
.PictureFormat.CropLeft = 0
.PictureFormat.CropRight = 0
.PictureFormat.CropTop = 0
.PictureFormat.CropBottom = 0
.PictureFormat.TransparencyColor = RGB(255, 255, 255)
watermark.Copy
.Select
ActiveSheet.Paste
.Group.Select
Selection.ShapeRange.Align msoAlignCenters, True
Selection.ShapeRange.Align msoAlignMiddles, True
Selection.ShapeRange.Ungroup
.CopyPicture
With ActiveSheet.Pictures.Paste
.Left = 0
.Top = 0
End With
.Delete
End With
file = Dir
Loop
End Sub
```
这个代码会将指定目录下所有的 `.jpg` 格式图片打上居中的自定义水印并保存。你需要修改 `path` 变量为你的图片目录,并修改 `watermarkText` 变量为你想要的水印文本。也可以修改 `.jpg` 为其他格式的图片。
阅读全文