gif to webp

This commit is contained in:
2023-04-06 13:56:34 +08:00
parent 95c273d0b8
commit 2c1ddf07d2
3 changed files with 31 additions and 11 deletions

View File

@@ -2,20 +2,31 @@ package main
import (
"image"
"image/gif"
"log"
"net/http"
"os"
"runtime"
"regexp"
"strconv"
"github.com/chai2010/webp"
"github.com/disintegration/imaging"
giftowebp "github.com/sizeofint/gif-to-webp"
)
type Image struct {
FilePath string
Data []byte
ImageType int
Ext string
Width int
Height int
}
// 实现一个 web api 服务(获取指定尺寸的图片)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
http.HandleFunc("/img/", func(w http.ResponseWriter, r *http.Request) {
@@ -65,20 +76,27 @@ func main() {
// 如果是 GIF 格式的动态图片,直接返回
if ext == "gif" {
giffile, err := os.Open("data/test.gif")
gifBin, err := os.ReadFile("data/test.gif")
if err != nil {
log.Println("打开文件失败", err)
log.Println("读取文件失败", err)
w.WriteHeader(http.StatusBadRequest)
return
}
defer giffile.Close()
gifimg, err := gif.DecodeAll(giffile)
converter := giftowebp.NewConverter()
converter.LoopCompatibility = false
converter.WebPConfig.SetLossless(0) // 0 有损压缩 1无损压缩
converter.WebPConfig.SetMethod(6) // 压缩速度 0-6 0最快 6质量最好
converter.WebPConfig.SetQuality(10) // 压缩质量 0-100
converter.WebPAnimEncoderOptions.SetKmin(9)
converter.WebPAnimEncoderOptions.SetKmax(17)
webpBuf, err := converter.Convert(gifBin)
if err != nil {
log.Println("码图像失败", err)
log.Println("码图像失败", err.Error())
w.WriteHeader(http.StatusBadRequest)
return
}
gif.EncodeAll(w, gifimg)
w.Write(webpBuf)
return
}