Writing an Image Manipulation Library in Go — Part 3

Koray Göçmen
2 min readOct 14, 2020

Part 3 — Filtering images

Filtering can be done by increasing the R, G, B values of pixels by a specified percentage.

Side note: I chose to make these functions associated with my Image type. After creating an Image type from an image file, I can call these functions on the objects. This is the “object-oriented” method of doing things in Go. (well, not really: go is not an object-oriented language).

// Filter with "R", "G" or "B" values. Increase the given r/g/b values
// of pixel by the given percentage.
func (img *Image) Filter(color string, percentage float32) *Image {
var wg sync.WaitGroup

for rowIndex := 0; rowIndex < img.Height; rowIndex++ {
wg.Add(1)
go (func(rowIndex int, img *Image) {
for colIndex := 0; colIndex < img.Width; colIndex++ {
pixel := img.Pixels[rowIndex][colIndex]
enhanced := pixel.Get(color) * int(1+percentage)
if enhanced > 255 {
enhanced = 255
}
img.Pixels[rowIndex][colIndex] = pixel.Set(color, enhanced)
}
wg.Done()
})(rowIndex, img)
}

wg.Wait()
return img
}

Side note: This function actually manipulates all rows in parallel. By using sync.WaitGroup and go keyword, I am able to do things concurrently. I actually wrote a blog post about concurrency in go: Concurrency and mutex locks in Go

There is really not much to filtering, I increase the pixel value of the specified colour by the specified percentage. And after increasing the pixel value if it is over 255, I max it out at 255 since I am using an 8-bit colour dept and the max value for an 8-bit colour dept is 255.

That’s filtering.

That’s what I have so far. I might work on this in the future. I wrote this code mostly to test different things and learn about the standard image package and how to work with it. The code and the tests for the code are on my Github repo: github.com/KorayGocmen/image

--

--

Koray Göçmen

University of Toronto, Computer Engineering, architected and implemented reliable infrastructures and worked as the lead developer for multiple startups.