WhspBrd/pkg/render_image/render_image.go
copilot-swe-agent[bot] cfedfd3550 Refactor codebase: fix formatting, error handling, and remove magic numbers
Co-authored-by: foglar <82380203+foglar@users.noreply.github.com>
2025-10-09 09:06:18 +00:00

76 lines
1.5 KiB
Go

package render_image
import (
"encoding/base64"
"fmt"
"image"
"image/draw"
_ "image/jpeg"
_ "image/png"
"os"
"whspbrd/pkg/resize_image"
)
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, width int, height int, units bool) {
img, err := LoadImage(filepath)
if err != nil {
fmt.Printf("Error loading image: %v\n", err)
return
}
rgba := ConvertToRGBA(img)
if units {
rgba, _ = resize_image.ResizeInTerminal(*rgba, width, height)
} else {
rgba, _ = resize_image.Resize(*rgba, width, height)
}
encoded := EncodeImageToBase64RGBA(rgba)
imgWidth := rgba.Rect.Dx()
imgHeight := rgba.Rect.Dy()
fmt.Printf("\033[s\033[%d;%dH", row, col)
chunkSize := 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,", imgWidth, imgHeight)
first = false
}
chunkLen := len(encoded) - pos
if chunkLen > chunkSize {
chunkLen = chunkSize
}
if pos+chunkLen < len(encoded) {
fmt.Print("m=1")
}
fmt.Printf(";%s\033\\", encoded[pos:pos+chunkLen])
pos += chunkLen
}
fmt.Print("\033[u")
}