Skip to content

Instantly share code, notes, and snippets.

@mazrean
Last active May 11, 2022 19:29
Show Gist options
  • Save mazrean/e5910cf6c09ba18f28e3e10983a98c18 to your computer and use it in GitHub Desktop.
Save mazrean/e5910cf6c09ba18f28e3e10983a98c18 to your computer and use it in GitHub Desktop.
Golang Image Square Resize
package main
import (
"flag"
"fmt"
"image"
"image/draw"
"image/png"
"os"
"path/filepath"
)
var (
dir string
)
func init() {
flag.StringVar(&dir, "dir", ".", "directory to read")
flag.Parse()
}
func main() {
entries, err := os.ReadDir(dir)
if err != nil {
panic(err)
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
ext := filepath.Ext(entry.Name())
if ext != ".png" {
continue
}
fileName := filepath.Base(entry.Name())
baseName := fileName[:len(fileName)-len(ext)]
f, err := os.Open(filepath.Join(dir, entry.Name()))
if err != nil {
panic(err)
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
panic(err)
}
bounds := img.Bounds()
w := bounds.Dx()
h := bounds.Dy()
if w == h {
continue
}
var (
resizedImg *image.RGBA
point image.Point
)
if w > h {
resizedImg = image.NewRGBA(image.Rect(0, 0, w, w))
point = image.Point{0, -(w - h) / 2}
} else {
resizedImg = image.NewRGBA(image.Rect(0, 0, h, h))
point = image.Point{-(h - w) / 2, 0}
}
draw.Draw(resizedImg, resizedImg.Bounds(), img, point, draw.Src)
out, err := os.OpenFile(filepath.Join(dir, fmt.Sprintf("%s_resized%s", baseName, ext)), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
panic(err)
}
defer out.Close()
err = png.Encode(out, resizedImg)
if err != nil {
panic(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment