Skip to content

Instantly share code, notes, and snippets.

@Noofbiz
Created June 7, 2017 17:47
Show Gist options
  • Save Noofbiz/7e21c97c2431b67d22d292852af77d02 to your computer and use it in GitHub Desktop.
Save Noofbiz/7e21c97c2431b67d22d292852af77d02 to your computer and use it in GitHub Desktop.
Takes all the pictures in the folder in, scales the image while maintaining aspect ratio as big as it can without exceeding 650 x 350, and then creates a 700 x 400 image of the same name in the out folder with a black background.
package main
import (
"image/color"
"io/ioutil"
"log"
"github.com/disintegration/imaging"
)
func main() {
pics, err := ioutil.ReadDir("in")
if err != nil {
log.Fatalf("Unable to read directory. Error: %v", err.Error())
}
for index := 0; index < len(pics); index++ {
inPath := "in/" + pics[index].Name()
outPath := "out/" + pics[index].Name()
i, err := imaging.Open(inPath)
if err != nil {
log.Fatalf("Unable to open file. Error: %v", err.Error())
}
if i.Bounds().Dx() >= i.Bounds().Dy() {
i = imaging.Resize(i, 650, 0, imaging.Lanczos)
} else {
i = imaging.Resize(i, 0, 350, imaging.Lanczos)
}
bg := imaging.New(700, 400, color.Black)
saveImg := imaging.PasteCenter(bg, i)
if err = imaging.Save(saveImg, outPath); err != nil {
log.Fatalf("Unable to save file. Error: %v", err.Error())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment