zoukankan      html  css  js  c++  java
  • go-chart go后端生成图表base64

    import (
    "github.com/golang/freetype/truetype"
    "github.com/wcharczuk/go-chart"
    "github.com/wcharczuk/go-chart/drawing"
    )

    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)) }

      

     
  • 相关阅读:
    This iPhone 6s is running iOS 11.3.1 (15E302), which may not be supported by this version of Xcode.
    vmware 里MAC 鼠标能移动 无法单击
    php获取微信的openid
    PHP 调试打印输出变量
    E0264 Unable to execute '"/usr/bin/codesign" ...'
    PHP 返回JSON
    小米手机安装证书
    CSS3:radial-gradient,径向渐变的使用方法
    CSS3:linear-gradient,线性渐变的使用方法
    CSS3:RGBA的使用方法
  • 原文地址:https://www.cnblogs.com/zipon/p/13891598.html
Copyright © 2011-2022 走看看