58 lines
1.4 KiB
Go
58 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/md5"
|
|
"fmt"
|
|
"github.com/disintegration/imaging"
|
|
"github.com/rs/zerolog/log"
|
|
"image/jpeg"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
func getImagePath(url string) (string, error) {
|
|
fileName := fmt.Sprintf("%x.png", md5.Sum([]byte(url)))
|
|
fileName, _ = getFilePath(fileName)
|
|
if _, err := os.Stat(fileName); os.IsNotExist(err) {
|
|
log.Printf("Download %s", url)
|
|
response, err := http.Get(url)
|
|
defer response.Body.Close()
|
|
if err != nil {
|
|
log.Printf("Failed to download Image: %v", err)
|
|
return "", fmt.Errorf("failed to download image")
|
|
}
|
|
if response.StatusCode != 200 {
|
|
log.Printf("Received non 200 response code: %v", response.StatusCode)
|
|
return "", fmt.Errorf("failed to download image")
|
|
}
|
|
|
|
i, err := jpeg.Decode(response.Body)
|
|
if err != nil {
|
|
log.Printf("Failed to decode Image: %v", err)
|
|
return "", fmt.Errorf("failed to decode image")
|
|
}
|
|
i = imaging.Resize(i, 150, 0, imaging.Lanczos)
|
|
err = imaging.Save(i, fileName)
|
|
if err != nil {
|
|
log.Printf("Failed to save Image: %v", err)
|
|
return "", fmt.Errorf("failed to save image")
|
|
}
|
|
}
|
|
return fileName, nil
|
|
}
|
|
|
|
func getFilePath(fileName string) (string, error) {
|
|
var path string
|
|
var err error
|
|
if filepath.IsAbs(fileName) {
|
|
path = fileName
|
|
} else {
|
|
path, err = filepath.Abs(filepath.Join(cfg.ImagePath, fileName))
|
|
if err != nil {
|
|
log.Error().Msg("Failed to splice path")
|
|
return "", fmt.Errorf("failed to splice path")
|
|
}
|
|
}
|
|
return path, nil
|
|
}
|