'Arithmetic Exception Swift
currently I am trying to create an App with Particle effects to match an image. When doing so I am frequently running into Arithmetic Exceptions when trying to read the image and process it in especially this method.
func getPixels() -> [[Int]] {
guard let cgImage = self.cgImage,
let data = cgImage.dataProvider?.data,
let bytes = CFDataGetBytePtr(data) else {
fatalError("Couldn't access image data")
}
var pixelMap = repeatElement(repeatElement(0, count: cgImage.height).map { $0 }, count: cgImage.width).map { $0 }
let bytesPerPixel = cgImage.bitsPerPixel / cgImage.bitsPerComponent
for y in 0 ..< cgImage.height {
for x in 0 ..< cgImage.width {
let offset = (y * cgImage.bytesPerRow) + (x * bytesPerPixel)
let components = (r: bytes[offset], g: bytes[offset + 1], b: bytes[offset + 2])
pixelMap[x][y] = Int((components.r + components.g + components.b)/3)
}
}
return pixelMap
}
In this line pixelMap[x][y] = Int((components.r + components.g + components.b)/3), I frequently get an Arithmetic Overflow and wanted to know if there is any possible way to resolve this error. I would assume that the full number couldn't be stored, but is there any way to store such a number, perhaps in a combination of integers? If so, how could I possibly implement that here?
Full source code can be found here, if desired: https://github.com/Alpheron/Particles
Solution 1:[1]
To convert MartinR's comment into code, the change would be here:
// First convert all the values to Int
let components = (r: Int(bytes[offset]), g: Int(bytes[offset + 1]), b: Int(bytes[offset + 2]))
// Then perform computations within the Int range.
// There's no need to convert at the end.
pixelMap[x][y] = (components.r + components.g + components.b)/3
This causes the + to operate on Int values rather than UInt8, ensuring there's sufficient range to perform the addition without overflowing.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rob Napier |
