61 lines
1.5 KiB
Go
61 lines
1.5 KiB
Go
package imaging
|
|
|
|
import (
|
|
domain "RenewCMS/internal/domain/image"
|
|
"bytes"
|
|
"image"
|
|
"image/jpeg"
|
|
"image/png"
|
|
|
|
"github.com/gen2brain/webp"
|
|
)
|
|
|
|
type encoder interface {
|
|
contentType() string
|
|
flattensTransparency() bool
|
|
encode(output *bytes.Buffer, source image.Image, quality int) error
|
|
}
|
|
|
|
type jpegEncoder struct{}
|
|
|
|
func (jpegEncoder) contentType() string { return "image/jpeg" }
|
|
|
|
func (jpegEncoder) flattensTransparency() bool { return true }
|
|
|
|
func (jpegEncoder) encode(output *bytes.Buffer, source image.Image, quality int) error {
|
|
return jpeg.Encode(output, source, &jpeg.Options{Quality: quality})
|
|
}
|
|
|
|
type pngEncoder struct{}
|
|
|
|
func (pngEncoder) contentType() string { return "image/png" }
|
|
|
|
func (pngEncoder) flattensTransparency() bool { return false }
|
|
|
|
func (pngEncoder) encode(output *bytes.Buffer, source image.Image, _ int) error {
|
|
return png.Encode(output, source)
|
|
}
|
|
|
|
type webpEncoder struct{}
|
|
|
|
func (webpEncoder) contentType() string { return "image/webp" }
|
|
|
|
func (webpEncoder) flattensTransparency() bool { return false }
|
|
|
|
func (webpEncoder) encode(output *bytes.Buffer, source image.Image, quality int) error {
|
|
return webp.Encode(output, source, webp.Options{Quality: quality})
|
|
}
|
|
|
|
var knownEncoders = map[domain.VariantFormat]encoder{
|
|
domain.FormatJPEG: jpegEncoder{},
|
|
domain.FormatPNG: pngEncoder{},
|
|
domain.FormatWebP: webpEncoder{},
|
|
}
|
|
|
|
var sourceFormats = map[string]domain.VariantFormat{
|
|
"jpeg": domain.FormatJPEG,
|
|
"png": domain.FormatPNG,
|
|
"webp": domain.FormatWebP,
|
|
"gif": domain.FormatPNG,
|
|
}
|