images.go

 1package image
 2
 3import (
 4	"fmt"
 5	"image"
 6	"os"
 7	"strings"
 8
 9	"github.com/charmbracelet/lipgloss"
10	"github.com/disintegration/imaging"
11	"github.com/lucasb-eyer/go-colorful"
12)
13
14func ValidateFileSize(filePath string, sizeLimit int64) (bool, error) {
15	fileInfo, err := os.Stat(filePath)
16	if err != nil {
17		return false, fmt.Errorf("error getting file info: %w", err)
18	}
19
20	if fileInfo.Size() > sizeLimit {
21		return true, nil
22	}
23
24	return false, nil
25}
26
27func ToString(width int, img image.Image) string {
28	img = imaging.Resize(img, width, 0, imaging.Lanczos)
29	b := img.Bounds()
30	imageWidth := b.Max.X
31	h := b.Max.Y
32	str := strings.Builder{}
33
34	for heightCounter := 0; heightCounter < h; heightCounter += 2 {
35		for x := range imageWidth {
36			c1, _ := colorful.MakeColor(img.At(x, heightCounter))
37			color1 := lipgloss.Color(c1.Hex())
38
39			var color2 lipgloss.Color
40			if heightCounter+1 < h {
41				c2, _ := colorful.MakeColor(img.At(x, heightCounter+1))
42				color2 = lipgloss.Color(c2.Hex())
43			} else {
44				color2 = color1
45			}
46
47			str.WriteString(lipgloss.NewStyle().Foreground(color1).
48				Background(color2).Render("▀"))
49		}
50
51		str.WriteString("\n")
52	}
53
54	return str.String()
55}
56
57func ImagePreview(width int, filename string) (string, error) {
58	imageContent, err := os.Open(filename)
59	if err != nil {
60		return "", err
61	}
62	defer imageContent.Close()
63
64	img, _, err := image.Decode(imageContent)
65	if err != nil {
66		return "", err
67	}
68
69	imageString := ToString(width, img)
70
71	return imageString, nil
72}