VB.NET算术运算导致溢出

时间:2014-04-10 19:13:51

标签: vb.net math

我有一个改变图像亮度的功能。

但是我收到错误“算术运算导致溢出。你可能不会除以0”。在行

bData.ByteData(ii) = CByte(bData.ByteData(ii) + (amount * (255 - bData.ByteData(ii)))) 'blue

“金额”是30。

我不确定我做错了什么。有人看到我的错误吗? 谢谢!

    Public Sub Brightness(Optional ByVal amount As Single = 0)
        OnFilterStarted()
        If amount = 0 Then Return
        Dim bData = BitmapData.LockBits(b)
        If amount > 0 Then
            For ii = bData.ByteData.GetLowerBound(0) To bData.ByteData.GetUpperBound(0) Step 4
                bData.ByteData(ii) = CByte(bData.ByteData(ii) + (amount * (255 - bData.ByteData(ii)))) 'blue
                bData.ByteData(ii + 1) = CByte(bData.ByteData(ii + 1) + (amount * (255 - bData.ByteData(ii + 1)))) 'green
                bData.ByteData(ii + 2) = CByte(bData.ByteData(ii + 2) + (amount * (255 - bData.ByteData(ii + 2)))) 'red
            Next
        Else
            For ii = bData.ByteData.GetLowerBound(0) To bData.ByteData.GetUpperBound(0) Step 4
                bData.ByteData(ii) = CByte(bData.ByteData(ii) - (Math.Abs(amount) * bData.ByteData(ii))) 'blue
                bData.ByteData(ii + 1) = CByte(bData.ByteData(ii + 1) - (Math.Abs(amount) * bData.ByteData(ii + 1))) 'green
                bData.ByteData(ii + 2) = CByte(bData.ByteData(ii + 2) - (Math.Abs(amount) * bData.ByteData(ii + 2))) 'red
            Next
        End If
        bData.UnlockBits()
        OnFilterFinished()
    End Sub

1 个答案:

答案 0 :(得分:1)

当发生这种情况时,向我们展示ByteData(ii)的值。我很确定结果超出了字节的边界。如果你乘以30,你就不会给自己太多的空间。你的溢出不是由分歧造成的。

示例,这将导致错误。

    Dim b As Byte
    Dim a As Single

    b = 128
    a = 30

    b += a * (255 - b)

它不会导致错误的唯一方法是,如果b等于255(感谢mafafu)。