46 lines
1.1 KiB
Go
46 lines
1.1 KiB
Go
package imaging
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/sha256"
|
|
"fmt"
|
|
"image"
|
|
_ "image/jpeg"
|
|
_ "image/png"
|
|
"time"
|
|
|
|
"high-loud-apps-labs/internal/domain"
|
|
|
|
"github.com/disintegration/imaging"
|
|
"github.com/gen2brain/webp"
|
|
)
|
|
|
|
func Optimized(attachmentID string, imgData []byte) (*domain.AttachmentVariant, []byte, error) {
|
|
img, _, err := image.Decode(bytes.NewReader(imgData))
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("декодирование изображения: %w", err)
|
|
}
|
|
|
|
optimizedImg := imaging.Fit(img, 1280, 1280, imaging.Lanczos)
|
|
|
|
var buf bytes.Buffer
|
|
if err := webp.Encode(&buf, optimizedImg, webp.Options{Quality: 80}); err != nil {
|
|
return nil, nil, fmt.Errorf("кодирование webp: %w", err)
|
|
}
|
|
|
|
data := buf.Bytes()
|
|
sha := sha256.Sum256(data)
|
|
|
|
v := &domain.AttachmentVariant{
|
|
AttachmentID: attachmentID,
|
|
Name: domain.VariantOptimized,
|
|
ContentType: "image/webp",
|
|
SizeBytes: int64(len(data)),
|
|
Width: optimizedImg.Bounds().Dx(),
|
|
Height: optimizedImg.Bounds().Dy(),
|
|
SHA256: sha[:],
|
|
CreatedAt: time.Now().UTC(),
|
|
}
|
|
return v, data, nil
|
|
}
|