Skip to content

Instantly share code, notes, and snippets.

@racecraftr
Last active February 23, 2023 23:22
Show Gist options
  • Save racecraftr/39708998522b217c3d83a0f4537943d9 to your computer and use it in GitHub Desktop.
Save racecraftr/39708998522b217c3d83a0f4537943d9 to your computer and use it in GitHub Desktop.
prints out a jpeg/png image as an ASCII .txt file. Play around with it a bit :D
package main
import (
"bufio"
"fmt"
"image"
"image/png"
"image/jpeg"
"io"
"os"
"strings"
)
var (
jump int = 10
)
func ClampJump(size int, cols int) int {
n := size/cols
if n < 1 {
n = 1
}
return n
}
const (
localPath = "go/imageStuff/" // set this to be the relative path from the go file where you put this code to the folder you have your images in.
shader = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
desiredDetail = 300
)
func GetCharFromShader(s float64, darkbg bool) rune {
index := int(s / 255.0 * float64(len(shader)))
if darkbg {
index = len(shader) - index
}
if index >= len(shader) {
index = len(shader) - 1
}
return rune(shader[index])
}
func GetPixels(file io.Reader) ([][]rune, error) {
img, _, err := image.Decode(file)
if err != nil {
return nil, err
}
bounds := img.Bounds()
width, height := bounds.Max.X, bounds.Max.Y
jump = ClampJump(width, desiredDetail)
fmt.Printf("dimensions of image: %d x %d", width, height)
var pixels [][]rune
for y := 0; y < height/(jump * 2); y++ {
var row []rune
for x := 0; x < width/jump; x++ {
r, g, b, _ := img.At(x * jump, y * jump * 2).RGBA()
r /= 255
g /= 255
b /= 255
s := 0.3*float64(r) + 0.59*float64(g) + 0.11*float64(b)
//fmt.Printf("s = %v\n", s)
char := GetCharFromShader(s, true)
row = append(row, char)
}
pixels = append(pixels, row)
}
return pixels, nil
}
func Check(e error) {
if e != nil {
panic(e)
}
}
func main() {
// get path
image.RegisterFormat("jpeg", "jpeg", jpeg.Decode, jpeg.DecodeConfig)
image.RegisterFormat("png", "png", png.Decode, png.DecodeConfig)
path := localPath + "<filename>" // filename must be either a png or jpeg image.
path = strings.TrimSuffix(path, "\n")
file, err := os.Open(path)
Check(err)
defer file.Close()
outputPath := localPath + "1.txt"
_ = os.Remove(outputPath)
output, err := os.Create(outputPath)
Check(err)
defer output.Close()
pixels, err := GetPixels(file)
Check(err)
writer := bufio.NewWriter(output)
for _, row := range pixels {
for _, c := range row {
writer.WriteRune(c)
}
writer.WriteRune('\n')
}
fmt.Println()
os.Exit(0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment