在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
const imgStrPrefix = "data:image/png;base64," func imgToStr(imgContent bytes.Buffer) string { return imgStrPrefix + base64.StdEncoding.EncodeToString(imgContent.Bytes()) } func loadTTF(filename string) (ttf *truetype.Font, err error) { ttfContent, err := ioutil.ReadFile(app.Cfg.Templatesdir + filename) if err != nil { return ttf, err } ttf, err = truetype.Parse(ttfContent) return } func ToBarChart(title string, data interface{}, xkey string, ykey string, ymin float64, ymax float64, isReverse bool) template.HTML { values := make([]chart.Value, 0) items, isSucc := data.([]map[string]interface{}) if !isSucc { logger.Errorf("传入数据不符合格式") return "" } if isReverse { for i := len(items) - 1; i >= 0; i-- { cValueTmp := chart.Value{ Value: items[i][ykey].(float64), Label: items[i][xkey].(string), } values = append(values, cValueTmp) } } else { for _, item := range items { cValueTmp := chart.Value{ Value: item[ykey].(float64), Label: item[xkey].(string), } values = append(values, cValueTmp) } } ttf, err := loadTTF("MSYH.TTF") if err != nil { logger.Warnf("加载字体失败:%v", err) } yrange := chart.ContinuousRange{ Min: ymin, Max: ymax, } graph := chart.BarChart{ Font: ttf, Title: title, TitleStyle: chart.Style{ Show: true, TextHorizontalAlign: chart.TextHorizontalAlignCenter, }, XAxis: chart.Style{ Show: true, StrokeWidth: 1, }, YAxis: chart.YAxis{ Name: "数量", Style: chart.Style{ Show: true, StrokeWidth: 1, }, Range: &yrange, ValueFormatter: func(v interface{}) string { if vf, isFloat := v.(float64); isFloat { vi := int64(vf) return fmt.Sprintf("%d", vi) } return "" }, }, Canvas: chart.Style{ Show: true, Padding: chart.Box{ Top: 4, IsSet: true, }, FillColor: drawing.Color{120, 9, 9, 9}, }, Background: chart.Style{ Padding: chart.Box{ Top: 40, }, }, Height: 512, BarWidth: 60, Bars: values, } //buffer := bytes.NewBuffer([]byte{}) var buffer bytes.Buffer //f,err := os.Create("chart.png") err = graph.Render(chart.PNG, &buffer) if err != nil { logger.Errorf("图表渲染错误:%v", err) } base64str := imgToStr(buffer) return template.HTML(fmt.Sprintf("<img src='%s' />", base64str)) }
|
请发表评论