repos / pico

pico services - prose.sh, pastes.sh, imgs.sh, feeds.sh, pgs.sh
git clone https://github.com/picosh/pico.git

commit
2b0df2b
parent
cae0a48
author
Eric Bower
date
2023-01-15 16:07:29 +0000 UTC
fix(imgs): support uploading webp

We always intended to support `image/webp` but we never actually tested
the code path.
2 files changed,  +21, -5
M filehandlers/imgs/img.go
+16, -5
 1@@ -2,6 +2,7 @@ package uploadimgs
 2 
 3 import (
 4 	"bytes"
 5+	"errors"
 6 	"fmt"
 7 	"strings"
 8 
 9@@ -73,18 +74,28 @@ func (h *UploadImgHandler) metaImg(data *PostMetaData) error {
10 		opt.Lossless = false
11 	}
12 
13+	var webpReader *bytes.Reader
14 	contents := &bytes.Buffer{}
15+
16 	img, err := opt.GetImage(tee, data.MimeType)
17-	if err != nil {
18+	if errors.Is(err, shared.AlreadyWebP) {
19+		h.Cfg.Logger.Infof("(%s) is already webp, skipping encoding", data.Filename)
20+		webpReader = tee
21+	} else if err != nil {
22 		return err
23+	} else {
24+		err = opt.EncodeWebp(contents, img)
25+		if err != nil {
26+			return err
27+		}
28+
29+		webpReader = bytes.NewReader(contents.Bytes())
30 	}
31 
32-	err = opt.EncodeWebp(contents, img)
33-	if err != nil {
34-		return err
35+	if webpReader == nil {
36+		return fmt.Errorf("contents of webp file is nil")
37 	}
38 
39-	webpReader := bytes.NewReader(contents.Bytes())
40 	_, err = h.Storage.PutFile(
41 		bucket,
42 		fmt.Sprintf("%s.webp", shared.SanitizeFileExt(data.Filename)),
M shared/img.go
+5, -0
 1@@ -2,6 +2,7 @@ package shared
 2 
 3 import (
 4 	"bytes"
 5+	"errors"
 6 	"fmt"
 7 	"image"
 8 	gif "image/gif"
 9@@ -99,6 +100,8 @@ func GetRatio(dimes string) (*Ratio, error) {
10 	return ratio, nil
11 }
12 
13+var AlreadyWebP = errors.New("image is already webp")
14+
15 func (h *ImgOptimizer) GetImage(r io.Reader, mimeType string) (image.Image, error) {
16 	switch mimeType {
17 	case "image/png":
18@@ -109,6 +112,8 @@ func (h *ImgOptimizer) GetImage(r io.Reader, mimeType string) (image.Image, erro
19 		return jpeg.Decode(r)
20 	case "image/gif":
21 		return gif.Decode(r)
22+	case "image/webp":
23+		return nil, AlreadyWebP
24 	}
25 
26 	return nil, fmt.Errorf("(%s) not supported for optimization", mimeType)