Skip to content

Instantly share code, notes, and snippets.

@wesen
Created July 10, 2023 20:45
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 wesen/2e72f52fff75ac48e1b31363864ffc94 to your computer and use it in GitHub Desktop.
Save wesen/2e72f52fff75ac48e1b31363864ffc94 to your computer and use it in GitHub Desktop.
package main

import (
	"image/png"
	"os"
	"bufio"
	"encoding/base64"
	"fmt"

	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/code128"
	"github.com/fogleman/gg"
)

const (
	width  = 512
	height = 128
)

func main() {
	// Check for command line argument
	if len(os.Args) < 2 {
		panic("Usage: go run <program_name.go> (string to encode)")
	}

	// Generate a barcode
	bc, err := code128.Encode(os.Args[1])
	if err != nil {
		panic(err)
	}

	// Scale the barcode to fit
	bc, err = barcode.Scale(bc, width, height)
	if err != nil {
		panic(err)
	}

	// Draw the barcode to an image
	img := gg.NewContext(width, height)
	img.DrawRectangle(0, 0, float64(width), float64(height))
	img.Fill()

	img.DrawImage(bc, 0, 0)

	// Create a buffer to hold the PNG data
	imgBuffer := new(bytes.Buffer)
	err = png.Encode(imgBuffer, img.Image())
	if err != nil {
		panic(err)
	}

	// Convert PNG data to base64
	imgBase64Str := base64.StdEncoding.EncodeToString(imgBuffer.Bytes())

	// Print out the image directly to terminal using the Kitty terminal
	// protocol for rendering images in the terminal
	fmt.Printf("\x1b_Ga=d,f=100,%s\x1b\\\n", imgBase64Str)
}
package main

import (
	"encoding/base64"
	"fmt"
	"os"
)

// serializeGrCommand serializes Graphics Protocol command.
func serializeGrCommand(cmd map[string]string, payload []byte) []byte {
	res := []byte("\033_G")
	for k, v := range cmd {
		res = append(res, []byte(fmt.Sprintf("%s=%s,", k, v))...)
	}
	if len(payload) > 0 {
		res = append(res, ';')
		res = append(res, payload...)
	}
	res = append(res, '\033', '\\')
	return res
}

// writeChunked writes chunked Graphics Protocol command.
func writeChunked(cmd map[string]string, data []byte) {
	encoded := base64.StdEncoding.EncodeToString(data)
	const blockSize = 4096
	for len(encoded) > 0 {
		var block string
		if len(encoded) > blockSize {
			block, encoded = encoded[:blockSize], encoded[blockSize:]
		} else {
			block, encoded = encoded, ""
			cmd["m"] = "0"
		}
		payload := []byte(block)
		os.Stdout.Write(serializeGrCommand(cmd, payload))
		cmd = make(map[string]string)
	}
}

// outputPng outputs PNG image to Kitty Terminal.
func outputPng(s []byte) {
	cmd := map[string]string{
		"a": "T",
		"f": "100",
		"m": "1",
	}
	writeChunked(cmd, s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment