Skip to content

Commit

Permalink
Initial code to resize images
Browse files Browse the repository at this point in the history
  • Loading branch information
ThisIsNoahEvans committed Nov 6, 2023
1 parent 59dfeaa commit b3f034a
Show file tree
Hide file tree
Showing 5 changed files with 88 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,6 @@

# Go workspace file
go.work

# macOS
.DS_Store
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module resizer

go 1.21.3

require github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
78 changes: 78 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package main

import (
"fmt"
"image"
_ "image/png"
"image/jpeg"
"os"
"strconv"
"strings"

"github.com/nfnt/resize"
)

func main() {
if len(os.Args) < 3 {
fmt.Println("Usage: resizer <image_path> <size> ...")
os.Exit(1)
}

imagePath := os.Args[1]
sizes := os.Args[2:]

// Open the file.
file, err := os.Open(imagePath)
if err != nil {
fmt.Println("Error opening file:", err)
os.Exit(1)
}
defer file.Close()

// Decode the image.
img, _, err := image.Decode(file)
if err != nil {
fmt.Println("Error decoding image:", err)
os.Exit(1)
}

for _, size := range sizes {
dimensions := strings.Split(size, "x")
var width, height uint
var err error

// Parse width and height.
width64, err := strconv.ParseUint(dimensions[0], 10, 64)
if err != nil {
fmt.Println("Invalid width:", err)
continue
}
width = uint(width64)

if len(dimensions) == 2 {
height64, err := strconv.ParseUint(dimensions[1], 10, 64)
if err != nil {
fmt.Println("Invalid height:", err)
continue
}
height = uint(height64)
} else {
height = width
}

// Resize the image.
m := resize.Resize(width, height, img, resize.Lanczos3)

// Create the output file.
out, err := os.Create(fmt.Sprintf("%s_%dx%d.jpg", strings.TrimSuffix(imagePath, ".png"), width, height))
if err != nil {
fmt.Println("Error creating file:", err)
continue
}
defer out.Close()

// Write the new image to file.
jpeg.Encode(out, m, nil)
fmt.Printf("Resized image to %dx%d and saved as %s_%dx%d.jpg\n", width, height, strings.TrimSuffix(imagePath, ".png"), width, height)
}
}
Binary file added resizer
Binary file not shown.

0 comments on commit b3f034a

Please sign in to comment.