73 lines
1.4 KiB
Go
73 lines
1.4 KiB
Go
package term_image
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"image"
|
|
"image/draw"
|
|
"image/png"
|
|
"os"
|
|
)
|
|
|
|
func LoadImage(filePath string) (image.Image, error) {
|
|
f, err := os.Open(filePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer f.Close()
|
|
img, _, err := image.Decode(f)
|
|
return img, err
|
|
}
|
|
|
|
func EncodeImageToBase64RGBA(img image.Image) image.Image {
|
|
rgba := image.NewRGBA(img.Bounds())
|
|
draw.Draw(rgba, rgba.Bounds(), img, image.Point{0, 0}, draw.Src)
|
|
fmt.Print(rgba)
|
|
return rgba
|
|
}
|
|
func EncodeImageToBase64(img image.Image) (string, error) {
|
|
var buf bytes.Buffer
|
|
err := png.Encode(&buf, img)
|
|
if err != nil {
|
|
return "", fmt.Errorf("Error encodeing image: %w", err)
|
|
}
|
|
|
|
encoded := base64.StdEncoding.EncodeToString(buf.Bytes())
|
|
return encoded, nil
|
|
}
|
|
|
|
func RenderImage(filepath string, row int, col int) {
|
|
img, err := LoadImage(filepath)
|
|
if err != nil {
|
|
fmt.Printf("Error loading image: %v\n", err)
|
|
return
|
|
}
|
|
|
|
EncodeImageToBase64RGBA(img)
|
|
encoded, err := EncodeImageToBase64(img)
|
|
|
|
fmt.Printf("\033[s\033[%d;%dH", row, col)
|
|
chunk_size := 4096
|
|
pos := 0
|
|
for pos < len(encoded) {
|
|
fmt.Print("\033_G")
|
|
if pos == 0 {
|
|
fmt.Print("q=2,a=T,f=100,")
|
|
}
|
|
remaining := len(encoded) - pos
|
|
chunk_len := remaining
|
|
if remaining > chunk_size {
|
|
chunk_len = chunk_size
|
|
}
|
|
if pos+chunk_len < len(encoded) {
|
|
fmt.Print("m=1")
|
|
}
|
|
fmt.Printf(";%s", encoded[pos:][:chunk_len])
|
|
fmt.Print("\033\\")
|
|
pos += chunk_len
|
|
}
|
|
fmt.Print("\033[u")
|
|
}
|
|
|