Last active
August 29, 2015 14:01
-
-
Save stuartnelson3/38aae40683a7a8a96e1e to your computer and use it in GitHub Desktop.
golang resize image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"os" | |
"fmt" | |
"github.com/nfnt/resize" | |
"image/jpeg" | |
"image" | |
) | |
func main() { | |
f, err := os.Open("original.jpg") | |
if err != nil { | |
fmt.Println("Error opening file: ", err) | |
os.Exit(1) | |
} | |
defer f.Close() | |
original, err := jpeg.Decode(f) | |
resizeWidth := float64(200) | |
scale := resizeWidth / float64(original.Bounds().Dx()) | |
width, height := Scale(original.Bounds(), scale) | |
img := resize.Resize(uint(width), uint(height), original, resize.Lanczos3) | |
resized, err := os.Create("resized.jpg") | |
if err != nil { | |
fmt.Println("Error creating file: ", err) | |
os.Exit(1) | |
} | |
defer resized.Close() | |
// write new image to file | |
jpeg.Encode(resized, img, nil) | |
} | |
func Scale(image image.Rectangle, scale float64) (width, height uint) { | |
return uint(float64(image.Dx()) * scale), uint(float64(image.Dy()) * scale) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment