├── Readme.md └── ascii.go /Readme.md: -------------------------------------------------------------------------------- 1 | 2 | # go-image-to-ascii 3 | 4 | Convert image to ascii. 5 | 6 | ```go 7 | import "github.com/ivolo/go-image-to-ascii" 8 | // .. 9 | 10 | f, err := os.Open("screenshot.png") 11 | img, err := png.Decode(f) 12 | fmt.Print(ascii.Convert(img)) 13 | ``` 14 | 15 | ![image](https://cloud.githubusercontent.com/assets/658544/10387777/1334b9c2-6e19-11e5-9671-1248fe2b541f.png) 16 | -------------------------------------------------------------------------------- /ascii.go: -------------------------------------------------------------------------------- 1 | package ascii 2 | 3 | import ( 4 | "bytes" 5 | "image" 6 | "strconv" 7 | "github.com/ivolo/go-x256" 8 | "github.com/mgutz/ansi" 9 | ) 10 | 11 | // thanks to IonicaBizau/image-to-ascii for algorithm 12 | func Convert(img image.Image) (str string) { 13 | var buffer bytes.Buffer 14 | size := img.Bounds().Max; 15 | pixels := ".,:;i1tfLCG08@" 16 | precision := (255*4) / (len(pixels)-1) 17 | 18 | // ansi color end constant 19 | reset := ansi.ColorCode("reset") 20 | 21 | for y := 0; y < size.Y; y += 1 { 22 | for x := 0; x < size.X; x += 1 { 23 | r, g, b, a := img.At(x, y).RGBA() 24 | sum := r >> 8 + g >> 8 + b >> 8 + a >> 8 25 | pixel := pixels[int(sum) / precision] 26 | // find the closest ansi color code 27 | code := x256.ClosestCode(uint8(r >> 8), uint8(g >> 8), uint8(b >> 8)) 28 | /// get the ansi color code 29 | color := ansi.ColorCode(strconv.Itoa(code)) 30 | 31 | // write the pixel 32 | buffer.WriteString(color) 33 | buffer.WriteString(string(pixel)) 34 | buffer.WriteString(reset) 35 | } 36 | buffer.WriteString("\n") 37 | } 38 | 39 | return buffer.String() 40 | } --------------------------------------------------------------------------------