Skip to content

Instantly share code, notes, and snippets.

@timnovis
Last active January 22, 2018 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timnovis/63454f1f2317f6997fa94cb7e1f53094 to your computer and use it in GitHub Desktop.
Save timnovis/63454f1f2317f6997fa94cb7e1f53094 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"image/jpeg"
"io/ioutil"
"math/rand"
"os"
"strings"
"time"
"github.com/dlion/goImgur"
"github.com/fogleman/gg"
"github.com/nfnt/resize"
)
func main() {
// Imgur client ID
imgurClientID := "YOUR_CLIENT_ID"
// Load fonts directory
fontFiles, err := ioutil.ReadDir("./fonts")
// Init empty array for fonts
fontArray := []string{}
// Parse command line arguments
args := os.Args
// Get meme text from 1st arg
text := args[1]
// Loop over files in fonts directory
for _, font := range fontFiles {
ttfName := font.Name()
// Get index of '.ttf' in font name to verify it's a valid font (prevents nasties like .DS_STORE)
ttfIndex := strings.Index(ttfName, ".ttf")
if ttfIndex > -1 {
// Push font path into font array
fontArray = append(fontArray, fmt.Sprintf("./fonts/%v", ttfName))
}
}
// Get two rands, one for font and one for image
rand.Seed(time.Now().Unix())
randFontIndex := rand.Int() % len(fontArray)
randImageIndex := rand.Int() % 14
// Load image file into memory
backgroundFile, err := os.Open(fmt.Sprintf("./backgrounds/%v.jpg", randImageIndex))
if err != nil {
panic(err)
}
// Decode background jpeg
backgroundDecoded, err := jpeg.Decode(backgroundFile)
if err != nil {
panic(err)
}
backgroundFile.Close()
// Create new graphics context
canvas := gg.NewContext(500, 500)
// Set text colour
canvas.SetRGB(1, 1, 1)
// Load random font, size 45
canvas.LoadFontFace(fontArray[randFontIndex], 45)
// Resize the background to 500x500 and draw to canvas at 0,0
canvas.DrawImage(resize.Resize(500, 500, backgroundDecoded, resize.Lanczos3), 0, 0)
// Draw the supplied text on to the canvas
canvas.DrawStringWrapped(text, 250, 250, 0.5, 0.5, 400, 2, 1)
// Save the final image to out.png
canvas.SavePNG("out.png")
// Upload the image to imgur
result, err := goImgur.Upload("out.png", imgurClientID)
if err != nil {
panic(err)
}
// Print json response from imgur api to stdout
fmt.Println(*result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment