Last active
March 7, 2016 08:41
-
-
Save suzaku/929d7ec02c0204666b3d to your computer and use it in GitHub Desktop.
Command line tool for saving a simple image to the specified path
This file contains hidden or 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 ( | |
"fmt" | |
"image" | |
"image/color" | |
"image/draw" | |
"image/jpeg" | |
"image/png" | |
"log" | |
"os" | |
"strings" | |
) | |
func main() { | |
if len(os.Args) != 2 { | |
log.Fatal("Please specify the path to save the generated image") | |
os.Exit(1) | |
} | |
imgPath := os.Args[1] | |
out, err := os.Create(imgPath) | |
if err != nil { | |
log.Fatal(err) | |
os.Exit(1) | |
} | |
width, height := 100, 100 | |
background := color.RGBA{0, 0xFF, 0, 0xCC} | |
img := createImage(width, height, background) | |
if strings.HasSuffix(strings.ToLower(imgPath), ".jpg") { | |
var opt jpeg.Options | |
opt.Quality = 80 | |
err = jpeg.Encode(out, img, &opt) | |
} else { | |
err = png.Encode(out, img) | |
} | |
if err != nil { | |
log.Fatal(err) | |
os.Exit(1) | |
} | |
fmt.Printf("Image saved to %s\n", imgPath) | |
} | |
func createImage(width int, height int, background color.RGBA) *image.RGBA { | |
rect := image.Rect(0, 0, width, height) | |
img := image.NewRGBA(rect) | |
draw.Draw(img, img.Bounds(), &image.Uniform{background}, image.ZP, draw.Src) | |
return img | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment