tss-rocks/backend/pkg/imageutil/processor.go
CDN 05ddc1f783
Some checks failed
Build Backend / Build Docker Image (push) Successful in 3m33s
Test Backend / test (push) Failing after 31s
[feature] migrate to monorepo
2025-02-21 00:49:20 +08:00

59 lines
1.2 KiB
Go

package imageutil
import (
"bytes"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"github.com/chai2010/webp"
)
type ProcessOptions struct {
Lossless bool
Quality float32 // 0-100
Compression int // 0-6
}
// DefaultOptions returns default processing options
func DefaultOptions() ProcessOptions {
return ProcessOptions{
Lossless: true,
Quality: 90,
Compression: 4,
}
}
// ProcessImage converts any supported image to WebP format
func ProcessImage(input io.Reader, opts ProcessOptions) ([]byte, error) {
// Decode the original image
img, _, err := image.Decode(input)
if err != nil {
return nil, fmt.Errorf("failed to decode image: %w", err)
}
// Encode to WebP
var buf bytes.Buffer
if err := webp.Encode(&buf, img, &webp.Options{
Lossless: opts.Lossless,
Quality: opts.Quality,
Exact: true,
}); err != nil {
return nil, fmt.Errorf("failed to encode to WebP: %w", err)
}
return buf.Bytes(), nil
}
// IsImageFormat checks if the given format is a supported image format
func IsImageFormat(contentType string) bool {
switch contentType {
case "image/jpeg", "image/png", "image/gif", "image/webp":
return true
default:
return false
}
}