我们经常要对一些图形进行各种处理,例如黑白显示、灰度、对比度调节、亮度调整等等。而这些需要使用大量的Win32 API的图形功能才能实现,这让很多人望而却步,今天我来介绍一种非常简单的方法——Office交互组件实现图像处理。
1)打开VB并创建一个新的工程
2)在“工程”->“引用”中添加“Microsoft Word Object xx.xx”。xx.xx代表版本号,例如12.00
3)保存工程。
4)在工程文件夹下创建一个空的word 文档(temp.doc)和一幅图片。
5)根据本文提供的效果图布局界面并编写代码。
]
(效果图1)
(效果图2)
代码如下:
'-------------------------------------------------------------------------------------------------------------------------------
'标题:图像处理 之 Office集成
'开发:Santook(QQ:120742353)
'日期:2008-09-05
'KeyWords: 图像处理、VBA、Office集成
'字典: ColorType....................图像颜色类型
' Contrast.....................图像对比度,有效范围 0~1
' Rotation.....................角度,有效范围0~360 ;注意:在复制到剪贴板后将自动调整到0,90,180,270,360。
' Brightness...................亮度,有效范围 0~1
'-------------------------------------------------------------------------------------------------------------------------------
Dim wd As New Word.Application '定义窗体级全局变量,防止重复操作导致多次创建WinWord的实例
Dim doc As New Word.Document
Dim sp As Word.Shape
Private Sub Command1_Click() '黑白模式
sp.PictureFormat.Contrast = 0.5
sp.PictureFormat.ColorType = 3
sp.Rotation = 0
doc.Range.Copy
Me.Image2.Picture = Clipboard.GetData
End Sub
Private Sub Command2_Click() '90度翻转
sp.PictureFormat.ColorType = 1
sp.PictureFormat.Contrast = 0.5
sp.Rotation = 90
doc.Range.Copy
Me.Image2.Picture = Clipboard.GetData
End Sub
Private Sub Command3_Click() '100%对比度
sp.PictureFormat.ColorType = 1
sp.Rotation = 0
sp.PictureFormat.Contrast = 1
doc.Range.Copy
Me.Image2.Picture = Clipboard.GetData
End Sub
Private Sub Command4_Click() '对比度自由设定
sp.PictureFormat.Contrast = Me.Slider1.Value / 10
doc.Range.Copy
Me.Image2.Picture = Clipboard.GetData
End Sub
Private Sub Command5_Click() '亮度自由设定
sp.PictureFormat.Brightness = Me.Slider2.Value / 10
doc.Range.Copy
Me.Image2.Picture = Clipboard.GetData
End Sub
Private Sub Command6_Click() '恢复为默认
sp.PictureFormat.ColorType = 1
sp.Rotation = 0
doc.Range.Copy
Me.Image2.Picture = Clipboard.GetData
End Sub
Private Sub Form_Load()
Set doc = wd.Documents.Open(CombinePath(App.Path, "temp.doc"))
Set sp = doc.Shapes.AddPicture(CombinePath(App.Path, "temp.jpg"))
wd.Visible = False
End Sub
Private Sub Form_Unload(Cancel As Integer) '退出程序时清理引用对象
Set sp = Nothing
doc.Close
Set doc = Nothing
wd.Quit False
Set wd = Nothing
End '显式申明退出
End Sub
Private Function CombinePath(ByVal path_name As String, ByVal file_name As String) As String '路径组合方法
CombinePath = IIf(Right(path_name, 1) = "/", path_name & file_name, path_name & "/" & file_name)
End Function
'程序的源代码可以在我csdn的空间中下载到