topfans/backend/services/laserCompositor/loader/image_loader.go
2026-06-03 22:19:22 +08:00

69 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package loader
import (
"fmt"
"image"
"image/png"
"net/http"
"strings"
"time"
// 支持 JPEG 解码
_ "image/jpeg"
)
var httpClient = &http.Client{
Timeout: 30 * time.Second,
}
// LoadImage 从 URL 下载并解码图片,返回 image.Image
func LoadImage(url string) (image.Image, error) {
url = strings.TrimSpace(url)
if url == "" {
return nil, fmt.Errorf("empty URL")
}
resp, err := httpClient.Get(url)
if err != nil {
return nil, fmt.Errorf("download failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("download returned HTTP %d", resp.StatusCode)
}
img, _, err := image.Decode(resp.Body)
if err != nil {
return nil, fmt.Errorf("decode failed: %w", err)
}
return img, nil
}
// LoadDecodePNG 下载并强制解码为 PNG获取 alpha 通道)
func LoadDecodePNG(url string) (image.Image, error) {
url = strings.TrimSpace(url)
if url == "" {
return nil, fmt.Errorf("empty URL")
}
resp, err := httpClient.Get(url)
if err != nil {
return nil, fmt.Errorf("download failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("download returned HTTP %d", resp.StatusCode)
}
img, err := png.Decode(resp.Body)
if err != nil {
// Fallback: try standard image decode
return LoadImage(url)
}
return img, nil
}