misc

Unnamed repository; edit this file 'description' to name the repository.
git clone git://git.alexwennerberg.com/misc
Log | Files | Refs | README | LICENSE

avatar.go (1937B) - raw


      1 // Generate a simple avatar based on a hash of your name
      2 //
      3 // Derived from Ted Unangst's Honk
      4 // https://humungus.tedunangst.com/r/honk/v/tip/f/avatar.go
      5 //
      6 // Copyright (c) 2019 Alex Wennerberg, Ted Unangst <tedu@tedunangst.com>
      7 //
      8 // Permission to use, copy, modify, and distribute this software for any
      9 // purpose with or without fee is hereby granted, provided that the above
     10 // copyright notice and this permission notice appear in all copies.
     11 //
     12 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     13 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     14 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     15 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     16 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     17 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     18 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     19 
     20 package main
     21 
     22 import (
     23 	"bytes"
     24 	"crypto/sha512"
     25 	"fmt"
     26 	"image"
     27 	"image/png"
     28 	"io/ioutil"
     29 	"os"
     30 )
     31 
     32 // Modify the four colors used
     33 var avatarcolors = [4][4]byte{
     34 	{0, 0, 0, 255},
     35 	{255, 255, 255, 255},
     36 	{172, 172, 172, 255},
     37 	{96, 96, 96, 255},
     38 }
     39 
     40 // x and y dimensions in pixels
     41 const size = 16
     42 
     43 func genAvatar(name string) []byte {
     44 	h := sha512.New()
     45 	h.Write([]byte(name))
     46 	s := h.Sum(nil)
     47 	// Mess with these numbers to change the size
     48 	img := image.NewNRGBA(image.Rect(0, 0, size, size))
     49 	for i := 0; i < size; i++ {
     50 		for j := 0; j < size; j++ {
     51 			p := i*img.Stride + j*4
     52 			xx := i/(size/4)*16 + j/(size/4)
     53 			x := s[xx]
     54 			for n := 0; n < 4; n++ {
     55 				img.Pix[p+n] = avatarcolors[x/64][n]
     56 			}
     57 		}
     58 	}
     59 	var buf bytes.Buffer
     60 	png.Encode(&buf, img)
     61 	return buf.Bytes()
     62 }
     63 
     64 func main() {
     65 	if len(os.Args) > 2 {
     66 		avatar := genAvatar(os.Args[1])
     67 		ioutil.WriteFile(os.Args[2], avatar, 0644)
     68 	} else {
     69 		fmt.Println("Usage: [script] name output_file.png")
     70 		os.Exit(1)
     71 	}
     72 }