images.go 1.5 KB

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