images.go 1.7 KB

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