63 lines
1.1 KiB
Go
63 lines
1.1 KiB
Go
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)
|
|
}
|
|
|
|
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
|
|
func getRandomImages(number int) []string {
|
|
rand.Seed(time.Now().UnixNano())
|
|
var images []string
|
|
dir := getImagesList("/home/gator/Photos/")
|
|
for i := 0; i < number; i++ {
|
|
index := rand.Intn(len(dir))
|
|
images = append(images, dir[index])
|
|
}
|
|
return images
|
|
}
|