To use parallel processing and concurrency for image manipulation in Go, you can follow these steps:
Step 1: Import the required Go standard packages:
import (
"image"
"image/color"
"image/jpeg"
"os"
)
Step 2: Load the image file:
file, err := os.Open("input.jpg")
if err != nil {
panic(err)
}
defer file.Close()
img, err := jpeg.Decode(file)
if err != nil {
panic(err)
}
Step 3: Define the number of Goroutines (parallel routines) you want to use:
numGoroutines := 8
Step 4: Divide the image into smaller chunks based on the number of Goroutines:
width := img.Bounds().Size().X
height := img.Bounds().Size().Y
chunkHeight := height / numGoroutines
remainder := height % numGoroutines
type imageChunk struct {
minY, maxY int
}
chunks := make([]imageChunk, numGoroutines)
startY := 0
for i := 0; i < numGoroutines; i++ {
chunkHeightAdjusted := chunkHeight
if i < remainder {
chunkHeightAdjusted += 1
}
chunks[i] = imageChunk{minY: startY, maxY: startY + chunkHeightAdjusted}
startY += chunkHeightAdjusted
}
Step 5: Define the image manipulation function that will be executed in parallel:
func manipulateImage(img image.Image, minY, maxY int) {
for y := minY; y < maxY; y++ {
for x := 0; x < width; x++ {
// Perform image manipulation logic here, e.g., invert colors
r, g, b, _ := img.At(x, y).RGBA()
newColor := color.RGBA{
R: uint8(255 - r/256),
G: uint8(255 - g/256),
B: uint8(255 - b/256),
A: 255,
}
img.(*image.RGBA).Set(x, y, newColor)
}
}
}
Step 6: Launch multiple Goroutines to perform image manipulation in parallel:
var wg sync.WaitGroup
for i := 0; i < numGoroutines; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
chunk := chunks[i]
manipulateImage(img, chunk.minY, chunk.maxY)
}(i)
}
wg.Wait() // Wait for all Goroutines to finish
Step 7: Save the modified image to file:
outputFile, err := os.Create("output.jpg")
if err != nil {
panic(err)
}
defer outputFile.Close()
jpeg.Encode(outputFile, img, nil)
This example divides the image into smaller chunks and assigns each chunk to a separate Goroutine, allowing for parallel image manipulation. By using Goroutines and concurrency, you can efficiently process images in parallel and speed up the overall execution time.