config.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package processing
  2. import (
  3. "errors"
  4. "fmt"
  5. "log/slog"
  6. "github.com/imgproxy/imgproxy/v3/config"
  7. "github.com/imgproxy/imgproxy/v3/ensure"
  8. "github.com/imgproxy/imgproxy/v3/imagetype"
  9. "github.com/imgproxy/imgproxy/v3/vips"
  10. )
  11. // Config holds pipeline-related configuration.
  12. type Config struct {
  13. PreferredFormats []imagetype.Type
  14. WatermarkOpacity float64
  15. DisableShrinkOnLoad bool
  16. UseLinearColorspace bool
  17. }
  18. // NewConfig creates a new Config instance with the given parameters.
  19. func NewDefaultConfig() Config {
  20. return Config{
  21. WatermarkOpacity: 1,
  22. PreferredFormats: []imagetype.Type{
  23. imagetype.JPEG,
  24. imagetype.PNG,
  25. imagetype.GIF,
  26. },
  27. }
  28. }
  29. // NewConfig creates a new Config instance with the given parameters.
  30. func LoadConfigFromEnv(c *Config) (*Config, error) {
  31. c = ensure.Ensure(c, NewDefaultConfig)
  32. c.WatermarkOpacity = config.WatermarkOpacity
  33. c.DisableShrinkOnLoad = config.DisableShrinkOnLoad
  34. c.UseLinearColorspace = config.UseLinearColorspace
  35. c.PreferredFormats = config.PreferredFormats
  36. return c, nil
  37. }
  38. // Validate checks if the configuration is valid
  39. func (c *Config) Validate() error {
  40. if c.WatermarkOpacity <= 0 {
  41. return errors.New("watermark opacity should be greater than 0")
  42. } else if c.WatermarkOpacity > 1 {
  43. return errors.New("watermark opacity should be less than or equal to 1")
  44. }
  45. filtered := c.PreferredFormats[:0]
  46. for _, t := range c.PreferredFormats {
  47. if !vips.SupportsSave(t) {
  48. slog.Warn(fmt.Sprintf("%s can't be a preferred format as it's saving is not supported", t))
  49. } else {
  50. filtered = append(filtered, t)
  51. }
  52. }
  53. if len(filtered) == 0 {
  54. return errors.New("no supported preferred formats specified")
  55. }
  56. c.PreferredFormats = filtered
  57. return nil
  58. }