69 lines
1.3 KiB
Go
69 lines
1.3 KiB
Go
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
|
||
}
|