[GH-25298] Place the text centered in default profile picture (#25324)

This commit is contained in:
Utsav Ladani 2024-02-19 20:35:51 +05:30 committed by GitHub
parent 97479800c2
commit dc9e404df0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 28 additions and 11 deletions

View File

@ -17,6 +17,7 @@ var (
DefaultFontError = errors.New("could not get default font") DefaultFontError = errors.New("could not get default font")
UserInitialsError = errors.New("could not get user initials") UserInitialsError = errors.New("could not get user initials")
ImageEncodingError = errors.New("could not encode image") ImageEncodingError = errors.New("could not encode image")
GlyphError = errors.New("could not get glyph")
) )
// ErrInvalidPassword indicates an error against the password settings // ErrInvalidPassword indicates an error against the password settings

View File

@ -22,6 +22,8 @@ import (
"github.com/mattermost/mattermost/server/public/model" "github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/v8/channels/utils/fileutils" "github.com/mattermost/mattermost/server/v8/channels/utils/fileutils"
"github.com/mattermost/mattermost/server/v8/platform/shared/filestore" "github.com/mattermost/mattermost/server/v8/platform/shared/filestore"
xfont "golang.org/x/image/font"
"golang.org/x/image/math/fixed"
) )
const ( const (
@ -141,24 +143,38 @@ func createProfileImage(username string, userID string, initialFont string) ([]b
} }
color := colors[int64(seed)%int64(len(colors))] color := colors[int64(seed)%int64(len(colors))]
dstImg := image.NewRGBA(image.Rect(0, 0, imageProfilePixelDimension, imageProfilePixelDimension)) dstImg := image.NewRGBA(image.Rect(0, 0, imageProfilePixelDimension, imageProfilePixelDimension))
srcImg := image.White
draw.Draw(dstImg, dstImg.Bounds(), &image.Uniform{color}, image.Point{}, draw.Src) draw.Draw(dstImg, dstImg.Bounds(), &image.Uniform{color}, image.Point{}, draw.Src)
size := float64(imageProfilePixelDimension / 2) size := float64(imageProfilePixelDimension / 2)
c := freetype.NewContext() opts := truetype.Options{}
c.SetFont(font) opts.Size = size
c.SetFontSize(size) face := truetype.NewFace(font, &opts)
c.SetClip(dstImg.Bounds())
c.SetDst(dstImg)
c.SetSrc(srcImg)
pt := freetype.Pt(imageProfilePixelDimension/5, imageProfilePixelDimension*2/3) d := &xfont.Drawer{
_, err = c.DrawString(initial, pt) Dst: dstImg,
if err != nil { Src: image.White,
return nil, UserInitialsError Face: face,
} }
bounds, advance, ok := face.GlyphBounds([]rune(initial)[0])
if !ok {
return nil, GlyphError
}
x := (fixed.I(imageProfilePixelDimension) - advance) / 2
y := (fixed.I(imageProfilePixelDimension) + (bounds.Max.Y - bounds.Min.Y)) / 2
d.Dot = fixed.Point26_6{
X: x,
Y: y,
}
d.DrawString(initial)
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
enc := png.Encoder{ enc := png.Encoder{