WhspBrd/term_image/render_image.go
2025-05-27 13:50:21 +02:00

72 lines
1.4 KiB
Go

package term_image
import (
"encoding/base64"
"fmt"
"image"
"image/draw"
"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 ConvertToRGBA(img image.Image) *image.RGBA {
rgba := image.NewRGBA(img.Bounds())
draw.Draw(rgba, rgba.Bounds(), img, image.Point{0, 0}, draw.Src)
return rgba
}
func EncodeImageToBase64RGBA(rgba *image.RGBA) string {
return base64.StdEncoding.EncodeToString(rgba.Pix)
}
func RenderImage(filepath string, row int, col int) {
img, err := LoadImage(filepath)
if err != nil {
fmt.Printf("Error loading image: %v\n", err)
return
}
rgba := ConvertToRGBA(img)
encoded := EncodeImageToBase64RGBA(rgba)
width := rgba.Rect.Dx()
height := rgba.Rect.Dy()
fmt.Printf("\033[s\033[%d;%dH", row, col)
chunk_size := 4096
pos := 0
first := true
for pos < len(encoded) {
fmt.Print("\033_G")
if first {
fmt.Printf("q=2,a=T,f=32,s=%d,v=%d,", width, height)
first = false
}
remaining := len(encoded) - pos
chunk_len := remaining
if chunk_len > chunk_size {
chunk_len = chunk_size
}
if pos+chunk_len < len(encoded) {
fmt.Print("m=1;")
} else {
fmt.Print(";")
}
fmt.Print(encoded[pos : pos+chunk_len])
fmt.Print("\033\\")
pos += chunk_len
}
fmt.Print("\033[u")
}