module_api_images.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package modules
  2. import (
  3. "bufio"
  4. "bytes"
  5. "path/filepath"
  6. "strings"
  7. "golang-fave/engine/wrapper"
  8. "github.com/disintegration/imaging"
  9. )
  10. func (this *Modules) api_GenerateImage(wrap *wrapper.Wrapper, width, height int, resize bool, filename string) ([]byte, bool, string, error) {
  11. file_ext := ""
  12. if strings.ToLower(filepath.Ext(filename)) == ".png" {
  13. file_ext = "image/png"
  14. } else if strings.ToLower(filepath.Ext(filename)) == ".jpg" {
  15. file_ext = "image/jpeg"
  16. } else if strings.ToLower(filepath.Ext(filename)) == ".jpeg" {
  17. file_ext = "image/jpeg"
  18. }
  19. src, err := imaging.Open(filename)
  20. if err != nil {
  21. return []byte(""), false, file_ext, err
  22. }
  23. if !resize {
  24. src = imaging.Fill(src, width, height, imaging.Center, imaging.Lanczos)
  25. } else {
  26. src = imaging.Fit(src, width, height, imaging.Lanczos)
  27. }
  28. var out_bytes bytes.Buffer
  29. out := bufio.NewWriter(&out_bytes)
  30. if file_ext == "image/png" {
  31. imaging.Encode(out, src, imaging.PNG)
  32. } else if file_ext == "image/jpeg" {
  33. imaging.Encode(out, src, imaging.JPEG)
  34. } else {
  35. return []byte(""), false, file_ext, nil
  36. }
  37. return out_bytes.Bytes(), true, file_ext, nil
  38. }