Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "image"
- "image/draw"
- "image/jpeg"
- "math"
- "os"
- "path/filepath"
- "strings"
- "github.com/nfnt/resize"
- "github.com/urfave/cli"
- )
- func getImagePaths(directory string) ([]string, error) {
- var imagePaths []string
- err := filepath.Walk(directory, func(path string, fi os.FileInfo, err error) error {
- if err != nil {
- return err
- }
- if fi.IsDir() {
- return nil
- }
- if strings.HasSuffix(path, "cover.jpg") ||
- strings.HasSuffix(path, "Cover.jpg") ||
- strings.HasSuffix(path, "folder.jpg") ||
- strings.HasSuffix(path, "front.jpg") {
- imagePaths = append(imagePaths, path)
- }
- return nil
- })
- if err != nil {
- return nil, err
- }
- return imagePaths, nil
- }
- func generateCollage(imagePaths []string, size int, columns int) {
- rows := int(math.Ceil(float64(len(imagePaths)) / float64(columns)))
- canvas := image.NewRGBA(image.Rect(0, 0, columns * size, rows * size))
- curCol, curRow := 0, 0
- for _, imagePath := range imagePaths {
- imageFile, err := os.Open(imagePath)
- if err != nil {
- panic(err)
- }
- img, _, err := image.Decode(imageFile)
- if err != nil {
- panic(err)
- }
- scaledImg := resize.Resize(uint(size), 0, img, resize.Lanczos3)
- sp := image.Point{curCol * size, curRow * size}
- rect := image.Rectangle{sp, sp.Add(image.Point{size, size})}
- draw.Draw(canvas, rect.Bounds(), scaledImg, image.Point{0, 0}, draw.Src)
- curCol = curCol + 1
- if curCol >= columns {
- curCol = 0
- curRow = curRow + 1
- }
- }
- out, err := os.Create("out.jpg")
- if err != nil {
- panic(err)
- }
- jpeg.Encode(out, canvas, &jpeg.Options{96})
- out.Close()
- }
- func main() {
- app := cli.NewApp()
- app.Name = "cover-collage"
- app.Version = "0.0.1"
- app.Flags = []cli.Flag{
- cli.IntFlag{Name: "size, s", Value: 120},
- cli.IntFlag{Name: "columns, c", Value: 8},
- }
- app.Action = func(ctx *cli.Context) error {
- if len(ctx.Args()) < 1 {
- fmt.Println("Incorrect Usage.\n")
- cli.ShowAppHelp(ctx)
- return nil
- }
- directory := ctx.Args()[0]
- imagePaths, _ := getImagePaths(directory)
- generateCollage(imagePaths, ctx.Int("size"), ctx.Int("columns"))
- return nil
- }
- app.Run(os.Args)
- }
Add Comment
Please, Sign In to add comment