【问题标题】:VB.NET Arithmetic operation caused an overflowVB.NET 算术运算导致溢出
【发布时间】:2014-04-10 19:13:50
【问题描述】:

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

但是我收到错误“算术运算导致溢出。您不能除以 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

【问题讨论】:

  • 在发生这种情况时向我们展示 ByteData(ii) 的值。我很确定结果超出了一个字节的边界。如果你乘以 30,你并没有给自己很多空间。你溢出不是由分裂引起的。
  • @the_lotus 确实如此。不会导致溢出的输入字节的唯一有效值是 255。
  • 重构代码会更好。

标签: vb.net math


【解决方案1】:

当这种情况发生时,向我们展示 ByteData(ii) 的值。我很确定结果超出了一个字节的边界。如果你乘以 30,你并没有给自己很多空间。你溢出不是由分裂引起的。

例如,这将导致错误。

    Dim b As Byte
    Dim a As Single

    b = 128
    a = 30

    b += a * (255 - b)

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

【讨论】:

    猜你喜欢
    • 2011-05-15
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多