go-chart
go-chart copied to clipboard
How to get a byte array via ImageWriter?
I'd like to get a byte array (i. e. []byte{...}) of my graph image. Now I use:
import (
"github.com/wcharczuk/go-chart"
"image/png"
"bytes"
)
...
func main() {
...
collector := chart.ImageWriter{}
graph.Render(chart.PNG, &collector) //where graph is my chart.Chart{...}
image, _ := collector.Image()
buffer := new(bytes.Buffer)
png.Encode(buffer, image)
byteArray := buffer.Bytes()
}
Is there a more efficient way to do it?
Yes, there is:
import (
"github.com/wcharczuk/go-chart"
"image/png"
"bytes"
)
...
func main() {
...
b := bytes.NewBuffer([]byte{})
graph.Render(chart.PNG, b) //where graph is my chart.Chart{...}
byteArray := b.Bytes()
}
graph.Render()
is already encoding to png. You are encoding the same data twice!