Skip to content
This repository has been archived by the owner on Jan 23, 2024. It is now read-only.

Commit

Permalink
fix: handle for different image format
Browse files Browse the repository at this point in the history
  • Loading branch information
AH-dark committed Jan 7, 2024
1 parent 83d40cd commit 4850855
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 8 deletions.
5 changes: 2 additions & 3 deletions services/avatar/get_gravatar.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"github.com/imroc/req/v3"
"github.com/samber/lo"
"image"
"image/jpeg"
"strconv"
"time"

Expand Down Expand Up @@ -71,9 +70,9 @@ func (s *service) getGravatar(ctx context.Context, hash string, args GetAvatarAr

defer resp.Body.Close()

img, err := jpeg.Decode(resp.Body)
img, err := parseImage(resp.GetHeader("Content-Type"), resp.Body)
if err != nil {
otelzap.L().Ctx(ctx).Error("failed to decode gravatar", zap.Error(err))
otelzap.L().Ctx(ctx).Error("parse image failed", zap.Error(err))
return GetGravatarResult{}, err
}

Expand Down
9 changes: 4 additions & 5 deletions services/avatar/get_qq_avatar.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ package avatar
import (
"context"
"fmt"
"github.com/imroc/req/v3"
"go.uber.org/zap"
"image"
"image/jpeg"
"strconv"

"github.com/imroc/req/v3"
"github.com/nfnt/resize"
"github.com/uptrace/opentelemetry-go-extra/otelzap"
"go.uber.org/zap"
)

func initQQClient() *req.Client {
Expand Down Expand Up @@ -67,9 +66,9 @@ func (s *service) getQQAvatar(ctx context.Context, hash string, args GetAvatarAr

defer resp.Body.Close()

img, err := jpeg.Decode(resp.Body)
img, err := parseImage(resp.GetHeader("Content-Type"), resp.Body)
if err != nil {
otelzap.L().Ctx(ctx).Error("decode qq avatar failed", zap.Error(err))
otelzap.L().Ctx(ctx).Error("parse image failed", zap.Error(err))
return nil, err
}

Expand Down
27 changes: 27 additions & 0 deletions services/avatar/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package avatar

import (
"github.com/kolesa-team/go-webp/webp"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
)

func parseImage(contentType string, reader io.Reader) (img image.Image, err error) {
switch contentType {
case "image/jpeg":
img, err = jpeg.Decode(reader)
case "image/png":
img, err = png.Decode(reader)
case "image/webp":
img, err = webp.Decode(reader, nil)
case "image/gif":
img, err = gif.Decode(reader)
default:
img, err = jpeg.Decode(reader)
}

return
}

0 comments on commit 4850855

Please sign in to comment.