@@ -25,32 +25,48 @@ class ImageService {
25
25
const background = composition . scenes [ 0 ] ?. background ;
26
26
27
27
if ( background ?. url ) {
28
- const avatarImageBuffer =
29
- await this . imageApi . getImageBuffer ( avatarImage ) ;
30
28
const backgroundImageBuffer = await this . imageApi . getImageBuffer (
31
29
background . url ,
32
30
) ;
33
31
34
- const previewBuffer = await this . composeImages (
35
- avatarImageBuffer ,
32
+ return await this . combineAvatarWithBackground (
33
+ avatarImage ,
36
34
backgroundImageBuffer ,
37
35
) ;
38
-
39
- const fileName = `preview_${ Date . now ( ) } .jpg` ;
40
-
41
- await this . fileService . uploadFile ( previewBuffer , fileName ) ;
42
-
43
- return this . fileService . getCloudFrontFileUrl ( fileName ) ;
44
36
}
45
37
46
38
if ( background ?. color ) {
47
- // TODO: create empty image with bg color
48
- // then combine avatar and this new image
39
+ const backgroundColorImageBuffer =
40
+ await this . createImageWithBackgroundColor ( background . color ) ;
41
+
42
+ return await this . combineAvatarWithBackground (
43
+ avatarImage ,
44
+ backgroundColorImageBuffer ,
45
+ ) ;
49
46
}
50
47
51
48
return avatarImage ;
52
49
}
53
50
51
+ private async combineAvatarWithBackground (
52
+ avatarImage : string ,
53
+ background : Buffer ,
54
+ ) : Promise < string > {
55
+ const avatarImageBuffer =
56
+ await this . imageApi . getImageBuffer ( avatarImage ) ;
57
+
58
+ const previewBuffer = await this . composeImages (
59
+ avatarImageBuffer ,
60
+ background ,
61
+ ) ;
62
+
63
+ const fileName = `preview_${ Date . now ( ) } .jpg` ;
64
+
65
+ await this . fileService . uploadFile ( previewBuffer , fileName ) ;
66
+
67
+ return this . fileService . getCloudFrontFileUrl ( fileName ) ;
68
+ }
69
+
54
70
private async composeImages (
55
71
avatar : Buffer ,
56
72
background : Buffer ,
@@ -73,6 +89,21 @@ class ImageService {
73
89
. composite ( [ { input : resizedAvatar , blend : 'over' } ] )
74
90
. toBuffer ( ) ;
75
91
}
92
+
93
+ private async createImageWithBackgroundColor (
94
+ backgroundColor : string ,
95
+ ) : Promise < Buffer > {
96
+ return await sharp ( {
97
+ create : {
98
+ width : PREVIEW_WIDTH ,
99
+ height : PREVIEW_HEIGHT ,
100
+ channels : 3 ,
101
+ background : backgroundColor ,
102
+ } ,
103
+ } )
104
+ . toFormat ( 'png' )
105
+ . toBuffer ( ) ;
106
+ }
76
107
}
77
108
78
109
export { ImageService } ;
0 commit comments