44 lines
905 B
Go
44 lines
905 B
Go
|
|
package application
|
||
|
|
|
||
|
|
import (
|
||
|
|
"bytes"
|
||
|
|
"image"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
webp "github.com/deepteams/webp"
|
||
|
|
)
|
||
|
|
|
||
|
|
const generatedWebPQuality float32 = 90
|
||
|
|
|
||
|
|
func encodeRasterAssetAsWebP(data []byte, contentType string) ([]byte, string, error) {
|
||
|
|
if !shouldEncodeAssetAsWebP(contentType) {
|
||
|
|
return data, contentType, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
source, _, err := image.Decode(bytes.NewReader(data))
|
||
|
|
if err != nil {
|
||
|
|
return nil, "", err
|
||
|
|
}
|
||
|
|
|
||
|
|
var output bytes.Buffer
|
||
|
|
if err := webp.Encode(&output, source, &webp.EncoderOptions{
|
||
|
|
Quality: generatedWebPQuality,
|
||
|
|
Method: 4,
|
||
|
|
AlphaQuality: 100,
|
||
|
|
UseSharpYUV: true,
|
||
|
|
Exact: true,
|
||
|
|
}); err != nil {
|
||
|
|
return nil, "", err
|
||
|
|
}
|
||
|
|
return output.Bytes(), "image/webp", nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func shouldEncodeAssetAsWebP(contentType string) bool {
|
||
|
|
switch strings.ToLower(strings.TrimSpace(contentType)) {
|
||
|
|
case "image/png", "image/jpeg", "image/jpg":
|
||
|
|
return true
|
||
|
|
default:
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
}
|