index/misc

Misc scripts and tools
git clone https://git.alexwennerberg.com/misc

avatar.go@main

raw
7d9ed20 Add param to output image size alex wennerberg 2021-07-27 09:55:14+0700
...

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
20package main
21
22import (
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
33var 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
41const size = 500
42
43func 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			fmt.Println(x)
55			if x < 64 {
56				img.Pix[p+0] = avatarcolors[0][0]
57				img.Pix[p+1] = avatarcolors[0][1]
58				img.Pix[p+2] = avatarcolors[0][2]
59				img.Pix[p+3] = avatarcolors[0][3]
60			} else if x < 128 {
61				img.Pix[p+0] = avatarcolors[1][0]
62				img.Pix[p+1] = avatarcolors[1][1]
63				img.Pix[p+2] = avatarcolors[1][2]
64				img.Pix[p+3] = avatarcolors[1][3]
65			} else if x < 192 {
66				img.Pix[p+0] = avatarcolors[2][0]
67				img.Pix[p+1] = avatarcolors[2][1]
68				img.Pix[p+2] = avatarcolors[2][2]
69				img.Pix[p+3] = avatarcolors[2][3]
70			} else {
71				img.Pix[p+0] = avatarcolors[3][0]
72				img.Pix[p+1] = avatarcolors[3][1]
73				img.Pix[p+2] = avatarcolors[3][2]
74				img.Pix[p+3] = avatarcolors[3][3]
75			}
76		}
77	}
78	var buf bytes.Buffer
79	png.Encode(&buf, img)
80	return buf.Bytes()
81}
82
83func main() {
84	if len(os.Args) > 2 {
85		avatar := genAvatar(os.Args[1])
86		ioutil.WriteFile(os.Args[2], avatar, 0644)
87	} else {
88		fmt.Println("Usage: [script] name output_file.png")
89		os.Exit(1)
90	}
91}
92