config.go 1.7 KB

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