无损压缩GIF

This commit is contained in:
2023-04-08 13:14:48 +08:00
parent feeea59c4b
commit 0b50f908ab
5 changed files with 186 additions and 83 deletions

View File

@@ -18,17 +18,61 @@ import (
)
func init() {
// 设置日志格式
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}
// 实现一个 web api 服务(获取指定尺寸的图片)
// string 转换为 int, 如果转换失败则返回默认值
func stringToInt(str string, defaultValue int) int {
if str == "" {
return defaultValue
}
value, err := strconv.Atoi(str)
if err != nil {
return defaultValue
}
return value
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
models.GetMysql() // 测试连接数据库
var mysqlConnection models.MysqlConnection
mysqlConnection.Init()
// 直接走 CDN 的请求不缓存本地, 因此直接使用参数
http.HandleFunc("/webp/", func(w http.ResponseWriter, r *http.Request) {
log.Println(r.Method, r.URL.Path)
// URL 格式: /img/{id}.{格式}?width=320&height=320&fit=cover
reg := regexp.MustCompile(`^/webp/([0-9a-zA-Z]+).(jpg|jpeg|png|webp)$`)
matches := reg.FindStringSubmatch(r.URL.Path)
if len(matches) != 3 {
log.Println("URL 格式错误", matches)
w.WriteHeader(http.StatusNotFound)
return
}
id, format, width, height, fit := matches[1], matches[2], stringToInt(r.URL.Query().Get("width"), 0), stringToInt(r.URL.Query().Get("height"), 0), r.URL.Query().Get("fit")
content, err := mysqlConnection.GetImageContent(id)
if err != nil {
log.Println("获取图片失败", format, err)
w.WriteHeader(http.StatusBadRequest)
}
var img models.Image
img.Init(content)
data, err := img.ToWebP(width, height, fit)
if err != nil {
log.Println("转换图片失败", err)
w.WriteHeader(http.StatusBadRequest)
}
w.Header().Set("Content-Type", "image/webp")
w.Header().Set("Cache-Control", "max-age=31536000")
w.Write(data)
})
http.HandleFunc("/img/", func(w http.ResponseWriter, r *http.Request) {
// URL 格式: /img/{id}-{version}@{倍图}{宽度}.{格式}
reg := regexp.MustCompile(`^/img/([0-9a-zA-Z]+)-([0-9a-zA-Z]+)@([0-9]{1,4})x([0-9]{1,4}).(jpg|jpeg|png|webp)$`)
matches := reg.FindStringSubmatch(r.URL.Path)