go-chart icon indicating copy to clipboard operation
go-chart copied to clipboard

How to get a byte array via ImageWriter?

Open vsile opened this issue 5 years ago • 1 comments

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?

vsile avatar Aug 31 '19 12:08 vsile

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!

MJacred avatar Feb 18 '20 15:02 MJacred