以下是一个使用Go语言编写的将图片转换为WebP格式的简单示例代码。这个示例使用了golang.org/x/image/webp包来进行WebP格式的转换。
首先,确保你已经安装了golang.org/x/image包及其依赖项。如果没有安装,可以使用以下命令安装:
go get -u golang.org/x/image
go get -u golang.org/x/image/webp
然后,你可以使用以下代码将JPEG或PNG图片转换为WebP格式:
package main
 
import (
    "bytes"
    "io/ioutil"
    "log"
    "net/http"
 
    "github.com/chai2010/webp"
)
 
func convertToWebP(imageData []byte) ([]byte, error) {
    src, err := webp.Decode(bytes.NewReader(imageData))
    if err != nil {
        return nil, err
    }
 
    buf := new(bytes.Buffer)
    err = webp.Encode(buf, src, &webp.Options{Lossless: true})
    if err != nil {
        return nil, err
    }
 
    return buf.Bytes(), nil
}
 
func handleConvert(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        return
    }
 
    file, _, err := r.FormFile("image")
    if err != nil {
        http.Error(w, "Failed to get image", http.StatusInternalServerError)
        log.Println(err)
        return
    }
    defer file.Close()
 
    imageData, err := ioutil.ReadAll(file)
    if err != nil {
        http.Error(w, "Failed to read image", http.StatusInternalServerError)
        log.Println(err)
        return
    }
 
    webpData, err := convertToWebP(imageData)
    if err != nil {
        http.Error(w, "Failed to convert image", http.StatusInternalServerError)
        log.Println(err)
        return
    }
 
    w.Header().Set("Content-Disposition", `attachment; filename="converted.webp"`)
    w.Write(webpData)
}
 
func main() {
    http.HandleFunc("/convert", handleConvert)
    log.Fatal(http.ListenAndServe(":8080", nil))
}
这段代码创建了一个简单的Web服务器,提供了一个/convert端点,用于接收POST请求,其中包含名为image的文件字段。服务器读取该文件,将其转换为WebP格式,并将转换后的图片作为附件返回。
确保你有一个适合Go语言的开发环境,并且已经安装了golang.org/x/image/webp包。然后,运行上述代码,并通过HTTP POST请求发送JPEG或PNG图片来测试转换功能。