Sourav
Sourav

Reputation: 17530

Simple some function returns "Overflow Exception"

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 !

Upvotes: 1

Views: 233

Answers (1)

Holger Brandt
Holger Brandt

Reputation: 4354

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))

Upvotes: 3

Related Questions