pixelweaver/fs.go

60 lines
1.1 KiB
Go
Raw Normal View History

package main
import (
"image"
"log"
"math/rand"
"os"
"path/filepath"
"strings"
"time"
)
// load an image from a file into an Image value
func loadImage(filename string) image.Image {
img, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer img.Close()
imgData, _, err := image.Decode(img)
if err != nil {
log.Fatal(err)
}
2022-05-01 09:07:46 +02:00
log.Println("Loading :", filename)
return imgData
}
// Walk through a folder recursively and returns a list of image paths
func getImagesList(path string) []string {
var imgs []string
err := filepath.Walk(path,
func(path string, info os.FileInfo, err error) error {
ext := strings.ToLower(filepath.Ext(path))
if err != nil {
return err
}
if ext == ".jpg" || ext == ".png" {
imgs = append(imgs, path)
}
return nil
})
if err != nil {
log.Println(err)
}
return imgs
}
// Randomly choose x number of image from a given folder
2022-05-01 09:15:49 +02:00
func getRandomImage() string {
rand.Seed(time.Now().UnixNano())
2022-05-01 09:48:37 +02:00
dir := getImagesList(ConfigRegister.InputDir)
2022-05-01 09:15:49 +02:00
index := rand.Intn(len(dir))
return dir[index]
}