0

I have a function that changes the brightness of an image.

However I am getting the error "Arithmetic operation caused an overflow. You may not divide by 0.". in the line

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

"amount" is 30.

I am not sure what I did wrong. Does anybody see my error? Thank you!

    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
3
  • Show us the value of ByteData(ii) when this happens. I'm pretty sure the result goes beyond the boundary of a byte. If you multiply by 30, you aren't giving yourself a lot of space. You're overflow isn't caused by a divide. Commented Apr 10, 2014 at 19:21
  • 2
    @the_lotus Indeed. The only valid value for the input byte that WON'T cause an overflow is 255. Commented Apr 10, 2014 at 19:22
  • Refactoring the code will be better. Commented Apr 10, 2014 at 19:22

1 Answer 1

1

Show us the value of ByteData(ii) when this happens. I'm pretty sure the result goes beyond the boundary of a byte. If you multiply by 30, you aren't giving yourself a lot of space. You're overflow isn't caused by a divide.

Example, this will cause the error.

    Dim b As Byte
    Dim a As Single

    b = 128
    a = 30

    b += a * (255 - b)

The only way for it to not cause an error is if b is equal to 255 (thanks mafafu).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.