img.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package img
  2. import (
  3. "fmt"
  4. "os"
  5. "os/exec"
  6. "path/filepath"
  7. "strings"
  8. "git.clearsky.net.au/cody/gex.git/gen/domquery"
  9. )
  10. func Process(htmlDir string, tag *domquery.Node) string {
  11. imgSrc := tag.GetAttribute("src")
  12. fileName := filepath.Base(imgSrc)
  13. if !strings.Contains(imgSrc, "app/") {
  14. imgSrc = htmlDir + "/" + imgSrc
  15. }
  16. imgSrc = strings.Replace(imgSrc, "/app/", "app/", 1)
  17. _, err := os.ReadFile(imgSrc)
  18. if err != nil {
  19. fmt.Println(err)
  20. return ""
  21. }
  22. w := tag.GetAttribute("w")
  23. h := tag.GetAttribute("h")
  24. cx := tag.GetAttribute("cx")
  25. if cx == "" {
  26. cx = "0"
  27. }
  28. cy := tag.GetAttribute("cy")
  29. if cy == "" {
  30. cy = "0"
  31. }
  32. cw := tag.GetAttribute("cw")
  33. if cw == "" {
  34. cw = "0"
  35. }
  36. ch := tag.GetAttribute("ch")
  37. if ch == "" {
  38. ch = "0"
  39. }
  40. q := tag.GetAttribute("q")
  41. command := "convert " + imgSrc + " -auto-orient"
  42. if w != "" || h != "" {
  43. command += " -resize " + w + "x" + h
  44. }
  45. if cw != "" && ch != "" {
  46. command += " -crop " + cw + "x" + ch + "+" + cx + "+" + cy
  47. }
  48. if q != "" {
  49. command += " -quality " + q
  50. }
  51. newImgSrc := "app/pub/gen/" + strings.Split(fileName, ".")[0] + w + h + cx + cy + cw + ch + q + ".webp"
  52. _, err = os.ReadFile(newImgSrc)
  53. if err == nil {
  54. tag.SetAttribute("src", "/"+newImgSrc)
  55. return ""
  56. } else {
  57. fmt.Println(err)
  58. }
  59. command += " " + newImgSrc
  60. cmd := exec.Command("bash", "-c", command)
  61. _, err = cmd.Output()
  62. if err != nil {
  63. fmt.Println(err)
  64. }
  65. tag.SetAttribute("src", "/"+newImgSrc)
  66. tag.RemoveAttribute("webp")
  67. tag.RemoveAttribute("w")
  68. tag.RemoveAttribute("h")
  69. tag.RemoveAttribute("cx")
  70. tag.RemoveAttribute("cy")
  71. tag.RemoveAttribute("cw")
  72. tag.RemoveAttribute("ch")
  73. return ""
  74. }