@@ -11,28 +11,27 @@ import (
1111 "image/color"
1212 "image/png"
1313
14- _ "image/gif" // for processing gif images
15- _ "image/jpeg" // for processing jpeg images
14+ "golang.org/x/image/draw"
1615
1716 "code.gitea.io/gitea/modules/avatar/identicon"
1817 "code.gitea.io/gitea/modules/setting"
1918
20- "golang.org/x/image/draw"
19+ _ "image/gif" // for processing gif images
20+ _ "image/jpeg" // for processing jpeg images
2121
2222 _ "golang.org/x/image/webp" // for processing webp images
2323)
2424
2525// DefaultAvatarSize is the target CSS pixel size for avatar generation. It is
26- // multiplied by setting.Avatar.RenderedSizeFactor and the resulting size is the
2726// usual size of avatar image saved on server, unless the original file is smaller
2827// than the size after resizing.
2928const DefaultAvatarSize = 256
3029
3130// RandomImageSize generates and returns a random avatar image unique to input data
3231// in custom size (height and width).
3332func RandomImageSize (size int , data []byte ) (image.Image , error ) {
34- // we use white as background, and use dark colors to draw blocks
35- imgMaker , err := identicon .New (size , color .White , identicon .DarkColors ... )
33+ // Use transparent background instead of white
34+ imgMaker , err := identicon .New (size , color .Transparent , identicon .DarkColors ... )
3635 if err != nil {
3736 return nil , fmt .Errorf ("identicon.New: %w" , err )
3837 }
@@ -85,18 +84,19 @@ func processAvatarImage(data []byte, maxOriginSize int64) ([]byte, error) {
8584 targetSize := DefaultAvatarSize * setting .Avatar .RenderedSizeFactor
8685 img = scale (img , targetSize , targetSize , draw .BiLinear )
8786
88- // try to encode the cropped/resized image to png
87+ // Create a new RGBA image to preserve transparency
88+ dst := image .NewRGBA (image .Rect (0 , 0 , img .Bounds ().Dx (), img .Bounds ().Dy ()))
89+ draw .Draw (dst , dst .Bounds (), image .Transparent , image.Point {}, draw .Src )
90+ draw .Draw (dst , img .Bounds (), img , img .Bounds ().Min , draw .Over )
91+
92+ // Encode the image to PNG with transparency
8993 bs := bytes.Buffer {}
90- if err = png .Encode (& bs , img ); err != nil {
94+ if err = png .Encode (& bs , dst ); err != nil {
9195 return nil , err
9296 }
9397 resized := bs .Bytes ()
9498
95- // usually the png compression is not good enough, use the original image (no cropping/resizing) if the origin is smaller
96- if len (data ) <= len (resized ) {
97- return data , nil
98- }
99-
99+ // Always use the processed image to ensure transparency
100100 return resized , nil
101101}
102102
0 commit comments