Reputation:
I would like to do sth like this in Go:
for x := 0; x < width; x++ {
for y := 0; y < height; y++ {
// something similar to this:
src_img[x, y] = color.Black
}
}
is it possible to do this, importing only "image", "image/jpeg", "image/color"?
Upvotes: 0
Views: 907
Reputation: 94699
The image.RGBA type is the preferred way to store images in memory if you want to modify them. It implements the draw.Image interface that has a convenient method for setting pixels:
Set(x, y int, c color.Color)
Unfortunately not all decoders are returning the images in the RGBA format. Some of them are leaving the image in a compressed format where not every single pixel is modifiable. That's much faster and fine for a lot of read-only use-cases. If you want to edit the image however, you might need to copy it. For example:
src, _, err := image.Decode(file)
if err != nil {
log.Fatal(err)
}
rgba, ok := src.(*image.RGBA)
if !ok {
b := src.Bounds()
rgba = image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
draw.Draw(rgba, rgba.Bounds(), src, b.Min, draw.Src)
}
// rgba is now a *image.RGBA and can be modified freely
rgba.Set(0, 0, color.RGBA{255, 0, 0, 255})
Upvotes: 2
Reputation: 91253
For example:
package main
import (
"fmt"
"image"
"image/color"
)
func main() {
const D = 12
img := image.NewGray(image.Rect(1, 1, D, D))
for x := 1; x <= D; x++ {
img.Set(x, x, color.Gray{byte(2 * x)})
}
for x := 1; x < D; x++ {
fmt.Printf("[%2d, %2d]: %5v\n", x, x, img.At(x, x))
}
}
Output:
[ 1, 1]: { 2}
[ 2, 2]: { 4}
[ 3, 3]: { 6}
[ 4, 4]: { 8}
[ 5, 5]: { 10}
[ 6, 6]: { 12}
[ 7, 7]: { 14}
[ 8, 8]: { 16}
[ 9, 9]: { 18}
[10, 10]: { 20}
[11, 11]: { 22}
Recomended reading The Go image package article (additionally to the godocs).
Upvotes: 2