Golang 气象数据渲染成图片
背景
已有气象接口,需要后端渲染生成图片。已经使用python3.7实现一个版本Python 气象数据渲染成图片,能够满足需求功能,也发现如下几个问题:
- 打包生成
exe
文件特别大:因为我引用一些第三方包,在打包时达到300M,一个小工具这是不能接受的 - 部署困难:我本地开发是win10,打包运行没有问题;服务器是Windows server 2008 ,在服务器上部署时提醒
api-ms-win-crt-runtime-l1-1-0.dll 丢失
,并且还需要按照python环境。
(注:本人不太熟悉python,可能有更好的解决方案)
使用Golang生成图片
-
生成图片的核心代码
package main import ( "image" "image/color" "image/color/palette" "image/png" "os" ) type WeatherData struct { code int msg string rows int cols int values [10][50] float32 } func main() { var wdatas WeatherData wdatas.code = 200 wdatas.msg = "success" wdatas.rows = 10 wdatas.cols = 50 var tvals = [10][50]float32{ {0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1}, {0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1}, {0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1}, {0, 0, 0.1, 0.5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 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1}, {0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1, 0, 0, 0.1, 0.5, 0.9, 0.7, 0, 0.6, 0, 1}, } wdatas.values = tvals const ( w, h int = 256, 256 R float64 = 50 // 大约一秒30帧 frameN int = 30 delay int = 100 / frameN ) // 216色 + 透明 var palette = append(palette.WebSafe, color.Transparent) var width = wdatas.cols var height = wdatas.rows img := image.NewPaletted(image.Rect(0, 0, width, height), palette) for x := 0; x < width; x++ { for y := 0; y < height; y++ { print(wdatas.values[y][x], " ") if wdatas.values[y][x] > 0.0 { img.Set(x, y, color.RGBA{255, 1, 1, 255}) } else { img.Set(x, y, color.Transparent) } //img.Set(x, y, color.Transparent) } println() } // 创建文件 file2, err := os.Create("test04.png") if err != nil { println("error...") } // 使用png格式将数据写入文件 png.Encode(file2, img) //将image信息写入文件中 // 关闭文件 file2.Close() }
结果
- 打包:使用
go build ***.go
打包,生成可以执行文件7.79M - 部署:直接拷贝就可以部署,没有其他问题