Browse Source

#2908

update
tags/v1.22.11.1^2
chenyifan01 3 years ago
parent
commit
3940775144
2 changed files with 32 additions and 0 deletions
  1. +1
    -0
      routers/badge/badge.go
  2. +31
    -0
      services/badge/icon.go

+ 1
- 0
routers/badge/badge.go View File

@@ -112,6 +112,7 @@ func UploadIcon(ctx *context.Context, form badge.IconUploadForm) {
FileMaxSize: setting.BadgeIconMaxFileSize, FileMaxSize: setting.BadgeIconMaxFileSize,
FileMaxWidth: setting.BadgeIconMaxWidth, FileMaxWidth: setting.BadgeIconMaxWidth,
FileMaxHeight: setting.BadgeIconMaxHeight, FileMaxHeight: setting.BadgeIconMaxHeight,
NeedSquare: true,
}) })
iconName, err := uploader.Upload(form, ctx.User) iconName, err := uploader.Upload(form, ctx.User)
if err != nil { if err != nil {


+ 31
- 0
services/badge/icon.go View File

@@ -8,6 +8,8 @@ import (
"crypto/md5" "crypto/md5"
"errors" "errors"
"fmt" "fmt"
"github.com/nfnt/resize"
"github.com/oliamb/cutter"
"image" "image"
"image/png" "image/png"
"io/ioutil" "io/ioutil"
@@ -27,6 +29,9 @@ type IconUploadConfig struct {
FileMaxSize int64 FileMaxSize int64
FileMaxWidth int FileMaxWidth int
FileMaxHeight int FileMaxHeight int
DefaultSize uint
NeedResize bool
NeedSquare bool
} }


func NewIconUploader(config IconUploadConfig) IconUploader { func NewIconUploader(config IconUploadConfig) IconUploader {
@@ -105,5 +110,31 @@ func (u IconUploader) prepare(data []byte) (*image.Image, error) {
return nil, fmt.Errorf("Decode: %v", err) return nil, fmt.Errorf("Decode: %v", err)
} }


if u.Config.NeedSquare {
if imgCfg.Width != imgCfg.Height {
var newSize, ax, ay int
if imgCfg.Width > imgCfg.Height {
newSize = imgCfg.Height
ax = (imgCfg.Width - imgCfg.Height) / 2
} else {
newSize = imgCfg.Width
ay = (imgCfg.Height - imgCfg.Width) / 2
}

img, err = cutter.Crop(img, cutter.Config{
Width: newSize,
Height: newSize,
Anchor: image.Point{ax, ay},
})
if err != nil {
return nil, err
}
}
}

if u.Config.NeedResize && u.Config.DefaultSize > 0 {
img = resize.Resize(u.Config.DefaultSize, u.Config.DefaultSize, img, resize.NearestNeighbor)
}

return &img, nil return &img, nil
} }

Loading…
Cancel
Save