Skip to content

Instantly share code, notes, and snippets.

@trevsm
Created December 11, 2022 07:27
Show Gist options
  • Save trevsm/e1499df702e0de7ad7d9db8d5520d3a9 to your computer and use it in GitHub Desktop.
Save trevsm/e1499df702e0de7ad7d9db8d5520d3a9 to your computer and use it in GitHub Desktop.
Compresses png files to 50% their original size using nearest-neighbor scaling algorithm
package main
import (
"fmt"
"image"
"image/png"
"io/ioutil"
"os"
)
func main() {
// Open the input file
inFile, err := os.Open("input.png")
if err != nil {
fmt.Println(err)
return
}
defer inFile.Close()
// Decode the input file into an image
img, err := png.Decode(inFile)
if err != nil {
fmt.Println(err)
return
}
// Scale the image to 50% of its original size
b := img.Bounds()
w, h := b.Max.X/2, b.Max.Y/2
scaledImg := image.NewNRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
scaledImg.Set(x, y, img.At(x*2, y*2))
}
}
// Encode the scaled image into a PNG
buf := new(bytes.Buffer)
err = png.Encode(buf, scaledImg)
if err != nil {
fmt.Println(err)
return
}
// Write the encoded image to a new file
err = ioutil.WriteFile("output.png", buf.Bytes(), 0644)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Image compressed successfully!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment