You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

76 lines
1.6 KiB

  1. package main
  2. import (
  3. "errors"
  4. "io/ioutil"
  5. "os"
  6. "sort"
  7. "strings"
  8. tfgo "codeberg.org/jlelse/tinify"
  9. )
  10. type ImageCompression interface {
  11. Compress(url string) (location string, err error)
  12. }
  13. // Tinify
  14. type Tinify struct {
  15. // API Key
  16. key string
  17. }
  18. func (t *Tinify) Compress(url string) (location string, err error) {
  19. fileExtension := func() string {
  20. spliced := strings.Split(url, ".")
  21. return spliced[len(spliced)-1]
  22. }()
  23. supportedTypes := []string{"jpg", "jpeg", "png"}
  24. sort.Strings(supportedTypes)
  25. i := sort.SearchStrings(supportedTypes, strings.ToLower(fileExtension))
  26. if !(i < len(supportedTypes) && supportedTypes[i] == strings.ToLower(fileExtension)) {
  27. err = errors.New("file not supported")
  28. return
  29. }
  30. tfgo.SetKey(t.key)
  31. s, e := tfgo.FromUrl(url)
  32. if e != nil {
  33. err = errors.New("failed to compress file")
  34. return
  35. }
  36. e = s.Resize(&tfgo.ResizeOption{
  37. Method: tfgo.ResizeMethodScale,
  38. Width: 2000,
  39. })
  40. if e != nil {
  41. err = errors.New("failed to resize file")
  42. return
  43. }
  44. file, e := ioutil.TempFile("", "tiny-*."+fileExtension)
  45. if e != nil {
  46. err = errors.New("failed to create temporary file")
  47. return
  48. }
  49. defer func() {
  50. _ = file.Close()
  51. _ = os.Remove(file.Name())
  52. }()
  53. e = s.ToFile(file.Name())
  54. if e != nil {
  55. err = errors.New("failed to save compressed file")
  56. return
  57. }
  58. hashFile, e := os.Open(file.Name())
  59. defer func() { _ = hashFile.Close() }()
  60. if e != nil {
  61. err = errors.New("failed to open temporary file")
  62. return
  63. }
  64. fileName, err := getSHA256(hashFile)
  65. if err != nil {
  66. return
  67. }
  68. location, err = SelectedMediaStorage.Upload(fileName+"."+fileExtension, file)
  69. return
  70. }