1

This code always through Arithmetic overflow exception. Whats wrong ?

Function ChannelSum(ByVal C As System.Drawing.Color) As Integer
    Dim temp As Integer : temp = (C.R + C.G + C.B)
    Return temp
End Function

...

Dim x, y, R, G, B, a As Integer : Dim tmp As Color
bmp = New Bitmap(picBox.Tag.ToString)
xMax = bmp.Width - 1 : yMax = bmp.Height - 1
For x = 0 To xMax Step 1
    For y = 0 To yMax Step 1
        tmp = bmp.GetPixel(x, y) : a = ChannelSum(tmp)
    Next y
Next x

The loop breaks in the first encounter !

7
  • On which line does the loop break? Commented Aug 2, 2012 at 14:50
  • The loop breaks in the first encounter ! When X and Y is 0, But the debugger shows X,Y have passed the xMax,yMax. I've copied all the code. Commented Aug 2, 2012 at 14:52
  • I would bet that your C.R,C.G,c.B are not returning an integer as you expect. Maybe you will need to do cInt on each of those. Commented Aug 2, 2012 at 14:54
  • What does that mean ? I'm using all the built in function. and valid color ranges from 0-255 and you are saying it's not returning INT. #confuzd :( Commented Aug 2, 2012 at 14:54
  • Exactly which line? Is it inside of ChannelSum function? Commented Aug 2, 2012 at 14:55

1 Answer 1

3

C.R and the others are byte fields and can only hold a value up to 255. Adding byte fields together will result in a number larger than 255. Use CInt() on each color element first.

 temp = (CInt(C.R) + CInt(C.G) + CInt(C.B))
Sign up to request clarification or add additional context in comments.

3 Comments

You can accept an answer in 4 minutes, So wait for 4 mins. Thnx :)
@Holger Brandt. Very weird, I'd thing it would detect that result is being assigned to an Integer variable.
@Trekstuff, actually, it always evaluates the expression on the right side of the equation first and then takes the results and tries to cast it into the datatype of the variable. Otherwise something like Dim tmp As String = 2 + 3 would probably show as "23" instead of "5".

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.