Products
96SEO 2025-07-04 15:53 25
`go
package main
import ( "crypto/sha1" "fmt" "image" "image/draw" "image/jpeg" "image/png" "io/ioutil" "log" "net/http" "os" "path/filepath" "strings" "sync"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
"golang.org/x/image/webp"
)
var ( fontData *truetype.Font bgImages []string allowedExts = []string{".jpg", ".jpeg", ".png", ".webp"} imageCache = sync.Map{} fontLoadError error )
func init() { // 初始化加載字體和背景圖片 loadResources() }
func loadResources() { // 加載字體 fontBytes, err := ioutil.ReadFile("../images/font.ttf") if err != nil { fontLoadError = fmt.Errorf("加載字體失敗: %v", err) return } fontData, err = freetype.ParseFont(fontBytes) if err != nil { fontLoadError = fmt.Errorf("解析字體失敗: %v", err) return }
// 加載背景圖片
dir := "../images/"
files, err := ioutil.ReadDir(dir)
if err != nil {
fontLoadError = fmt.Errorf("讀取圖片目錄失敗: %v", err)
return
}
for _, file := range files {
if file.IsDir() || strings.HasPrefix(file.Name(), ".") {
continue
}
ext := strings.ToLower(filepath.Ext(file.Name()))
for _, allowed := range allowedExts {
if ext == allowed && file.Name() != "font.ttf" {
bgImages = append(bgImages, filepath.Join(dir, file.Name()))
break
}
}
}
if len(bgImages) == 0 {
fontLoadError = fmt.Errorf("沒有找到可用的背景圖片")
}
}
func generateImage(text string) (image.Image, error) { if fontLoadError != nil { return nil, fontLoadError }
// 選擇背景圖片
h := sha1.New()
h.Write([]byte(text))
hash := h.Sum(nil)
idx := int(hash[0]) % len(bgImages)
bgPath := bgImages[idx]
// 檢查緩存
if img, ok := imageCache.Load(bgPath); ok {
// 復制一份避免修改緩存
bgImg := img.(image.Image)
rgba := image.NewRGBA(bgImg.Bounds())
draw.Draw(rgba, rgba.Bounds(), bgImg, image.Point{}, draw.Src)
return rgba, nil
}
// 加載圖片
file, err := os.Open(bgPath)
if err != nil {
return nil, fmt.Errorf("打開圖片失敗: %v", err)
}
defer file.Close()
var bgImg image.Image
ext := strings.ToLower(filepath.Ext(bgPath))
switch ext {
case ".png":
bgImg, err = png.Decode(file)
case ".webp":
bgImg, err = webp.Decode(file)
default: // jpg/jpeg
bgImg, err = jpeg.Decode(file)
}
if err != nil {
return nil, fmt.Errorf("解碼圖片失敗: %v", err)
}
// 緩存圖片
rgba := image.NewRGBA(bgImg.Bounds())
draw.Draw(rgba, rgba.Bounds(), bgImg, image.Point{}, draw.Src)
imageCache.Store(bgPath, rgba)
return rgba, nil
}
func addTextToImage(img image.Image, text string) (image.Image, error) { // 創(chuàng)建繪圖上下文 c := freetype.NewContext() c.SetDPI(72) c.SetFont(fontData) c.SetFontSize(36) c.SetClip(img.Bounds()) c.SetDst(img.(draw.Image)) c.SetSrc(image.White) c.SetHinting(font.HintingFull)
// 計算文字位置
pt := freetype.Pt(
(img.Bounds().Dx()-len(text)*20)/2, // 簡單估算寬度
100,
)
_, err := c.DrawString(text, pt)
if err != nil {
return nil, fmt.Errorf("繪制文字失敗: %v", err)
}
return img, nil
}
func imageHandler(w http.ResponseWriter, r *http.Request) { // 獲取參數(shù) text := r.URL.Query().Get("text") if text == "" { text = "默認文字" }
// 生成圖片
img, err := generateImage(text)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 添加文字
img, err = addTextToImage(img, text)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 設置響應頭
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Cache-Control", "public, max-age=31536000")
// 輸出圖片
err = jpeg.Encode(w, img, &jpeg.Options{Quality: 90})
if err != nil {
http.Error(w, "圖片編碼失敗", http.StatusInternalServerError)
}
}
func main() {
http.HandleFunc("/gen_img", imageHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
`
對于AnqiCMS,你需要:
在AnqiCMS的配置文件中添加以下路由規(guī)則:
yaml
routes:
- pattern: "/images/*path"
handler: "ImageHandler"
然后實現(xiàn)對應的ImageHandler
,或者直接使用反向代理到上面的Go服務。
對于Go站點,Nginx配置可以簡化為:
`nginx
location /images/ {
# 代理到Go服務
proxypass http://localhost:8080/genimg?text=$1;
proxysetheader Host $host;
# 緩存控制
expires max;
add_header Cache-Control "public";
# 錯誤處理
proxy_intercept_errors on;
error_page 404 = @img_rewrite;
}
location @imgrewrite {
rewrite ^/images/(.+)$ /genimg?text=$1 last;
}
`
img_gen.go
go get github.com/golang/freetype golang.org/x/image
go build img_gen.go
./img_gen
http://yoursite.com/gen_img?text=示例文字
http://yoursite.com/images/示例文字.jpg
這個Go實現(xiàn)方案比PHP版本更高效,且更適合集成到AnqiCMS等Go語言開發(fā)的站點中。
Demand feedback