Skip to content

Commit 0dcaca9

Browse files
committed
OV-423: * support background color for preview
1 parent 03aef74 commit 0dcaca9

File tree

1 file changed

+43
-12
lines changed

1 file changed

+43
-12
lines changed

backend/src/common/services/image/image.service.ts

+43-12
Original file line numberDiff line numberDiff line change
@@ -25,32 +25,48 @@ class ImageService {
2525
const background = composition.scenes[0]?.background;
2626

2727
if (background?.url) {
28-
const avatarImageBuffer =
29-
await this.imageApi.getImageBuffer(avatarImage);
3028
const backgroundImageBuffer = await this.imageApi.getImageBuffer(
3129
background.url,
3230
);
3331

34-
const previewBuffer = await this.composeImages(
35-
avatarImageBuffer,
32+
return await this.combineAvatarWithBackground(
33+
avatarImage,
3634
backgroundImageBuffer,
3735
);
38-
39-
const fileName = `preview_${Date.now()}.jpg`;
40-
41-
await this.fileService.uploadFile(previewBuffer, fileName);
42-
43-
return this.fileService.getCloudFrontFileUrl(fileName);
4436
}
4537

4638
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+
);
4946
}
5047

5148
return avatarImage;
5249
}
5350

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+
5470
private async composeImages(
5571
avatar: Buffer,
5672
background: Buffer,
@@ -73,6 +89,21 @@ class ImageService {
7389
.composite([{ input: resizedAvatar, blend: 'over' }])
7490
.toBuffer();
7591
}
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+
}
76107
}
77108

78109
export { ImageService };

0 commit comments

Comments
 (0)