如何用Vb.net实现两副图像的上下透明度混合
我使用的函数如下:
Public Function OpacityBlend(ByVal BackFile As String, ByVal ForFile As String, ByVal SrcImg As Bitmap, ByVal ForImg As Bitmap,
ByVal BackX As Integer, ByVal BackY As Integer, ByVal ForX As Integer,
ByVal ForY As Integer, ByVal W As Integer, ByVal H As Integer,
Optional ByVal SavePath As String = "", Optional ByVal Opacity As Single = 255) As Bitmap
Dim Bmp As Bitmap
If BackFile <> "" Then
Bmp = Bitmap.FromFile(BackFile)
Else
Bmp = SrcImg
End If
Dim ForBmp As Bitmap
If ForFile <> "" Then
ForBmp = Bitmap.FromFile(ForFile)
Else
ForBmp = ForImg
End If
Dim BmpDATA As New BitmapData
Dim TmpBMP As Bitmap = New Bitmap(Bmp)
Dim Rct As Rectangle = New Rectangle(0, 0, Bmp.Width, Bmp.Height)
BmpDATA = TmpBMP.LockBits(Rct, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb)
Dim BTS(BmpDATA.Stride * BmpDATA.Height) As Byte
Runtime.InteropServices.Marshal.Copy(BmpDATA.Scan0, BTS, 0, BTS.Length - 1)
Dim BmpForDATA As New BitmapData
Dim TmpForBMP As Bitmap = New Bitmap(ForBmp)
Dim RctFor As Rectangle = New Rectangle(0, 0, ForBmp.Width, ForBmp.Height)
BmpForDATA = TmpForBMP.LockBits(Rct, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb)
Dim BTSFor(BmpForDATA.Stride * BmpForDATA.Height) As Byte
Runtime.InteropServices.Marshal.Copy(BmpForDATA.Scan0, BTSFor, 0, BTSFor.Length - 1)
Dim T As Double = 0, x0 As Long, y0 As Long = -1, j As Integer
j = ForX * 4 * (ForY + 1)
For i As Integer = 0 To BTS.Length - 4 Step 4
If x0 = 0 Then y0 = y0 + 1
x0 = (i / 4) Mod Bmp.Width
If x0 >= BackX And x0 <= BackX + W Then
If y0 >= BackY And y0 <= BackY + H Then
BTS(i) = BlendColor(BTS(i), BTSFor(j), Opacity)
BTS(i + 1) = BlendColor(BTS(i + 1), BTSFor(j + 1), Opacity)
BTS(i + 2) = BlendColor(BTS(i + 2), BTSFor(j + 2), Opacity)
End If
j = j + 4
End If
Next
Runtime.InteropServices.Marshal.Copy(BTS, 0, BmpDATA.Scan0, BTS.Length - 1)
TmpBMP.UnlockBits(BmpDATA)
If SavePath <> "" Then
Dim Drv As String = SavePath.Substring(0, 1)
Dim ext As String = IO.Path.GetExtension(SavePath).ToLower
Dim Path As String = IO.Path.GetDirectoryName(SavePath)
Do
On Error Resume Next
TmpBMP.Save(SavePath)
If Err.Number = 61 Then
Shell("explorer.exe " & Path, 1)
Dim Rc As Integer = MsgBox("目标硬盘" & Drv & "磁盘空间不足,请释放磁盘空间后重试保存!", MsgBoxStyle.Critical + MsgBoxStyle.RetryCancel, "消息")
If Rc = MsgBoxResult.Cancel Then Exit Do
End If
Loop While Err.Number = 61
End If
Return TmpBMP
End Function
但是,得到的透明度混合后的图像如图所示,是坏的图像。哪位达人赐教,或者有何其他方法实现两幅图像的透明度混合?