Hi, I'm just starting to learn Go. I have a small pattern in a 5x5 array of
bools. I turn this into an image by looping through all of the values in
the array and using Image.Set if the value is true.
matrix := [5][5]bool{}
// fill in matrix here
m := image.NewRGBA(image.Rect(0, 0, 5, 5))
fg := color.RGBA{255, 0, 255, 255}
bg := color.RGBA{255, 255, 255, 255}
draw.Draw(m, m.Bounds(), &image.Uniform{bg}, image.ZP, draw.Src)
for x, row := range matrix {
for y, cell := range row {
if cell {
m.Set(x, y, fg)
}
}
}
Then I encode the image to a png and write it to the http.ResponseWriter
buffer := new(bytes.Buffer)
png.Encode(buffer, *img)
w.Write(buffer.Bytes())
It wasn't too slow, but I feel like I am doing something very wrong and
that it could be faster. I wrote a benchmark method in a test file with
ReportAllocs that calls the method in a loop and it reported that each call
was allocating memory 47 times so I'm sure that there's a better way to do
this.
I found the "github.com/oxtoacart/bpool" library which I can use to pool
the buffers I encode the png into, but after running with
GODEBUG=allocfreetrace=1 it shows that most of the allocations come from
creating the image, drawing the background and plotting all of the pixels.
Sorry if this post is a bit confusing or all over the place, tl;dr: How can
I quickly plot a 2D array of pixels onto a PNG that I can write to a
http.ResponseWriter?
Thanks :)
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.