render rgba image

This commit is contained in:
foglar 2025-05-27 13:50:21 +02:00
parent de37cd71fa
commit 0e727c5a5b

View File

@ -1,12 +1,10 @@
package term_image
import (
"bytes"
"encoding/base64"
"fmt"
"image"
"image/draw"
"image/png"
"os"
)
@ -20,21 +18,14 @@ func LoadImage(filePath string) (image.Image, error) {
return img, err
}
func EncodeImageToBase64RGBA(img image.Image) image.Image {
func ConvertToRGBA(img image.Image) *image.RGBA {
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 EncodeImageToBase64RGBA(rgba *image.RGBA) string {
return base64.StdEncoding.EncodeToString(rgba.Pix)
}
func RenderImage(filepath string, row int, col int) {
@ -44,26 +35,34 @@ func RenderImage(filepath string, row int, col int) {
return
}
EncodeImageToBase64RGBA(img)
encoded, err := EncodeImageToBase64(img)
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 pos == 0 {
fmt.Print("q=2,a=T,f=100,")
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 remaining > chunk_size {
if chunk_len > chunk_size {
chunk_len = chunk_size
}
if pos+chunk_len < len(encoded) {
fmt.Print("m=1")
fmt.Print("m=1;")
} else {
fmt.Print(";")
}
fmt.Printf(";%s", encoded[pos:][:chunk_len])
fmt.Print(encoded[pos : pos+chunk_len])
fmt.Print("\033\\")
pos += chunk_len
}