-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimageManipulator.js
60 lines (48 loc) · 1.62 KB
/
imageManipulator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import sharp from "sharp";
import axios from 'axios'
export async function downloadFileToBuffer(fileUrl) {
const arrayBuffer = await axios.get(fileUrl, {
responseType: 'arraybuffer'
});
return Buffer.from(arrayBuffer.data,'binary')
}
export async function addTextOnImage(text, img, avatarUrl, username) {
try {
const width = 750;
const height = 483;
const quoteSvg = `
<svg width="${width}" height="${height}">
<style>
.title { fill: #001; font-size: 70px; font-weight: bold;}
</style>
<text x="50%" y="50%" text-anchor="middle" class="title">${text}</text>
</svg>
`;
const svgUsername = `
<svg width="${width}" height="${height}">
<style>
.title { fill: #ffffff; font-size: 70px; font-weight: bold;}
</style>
<text x="50%" y="50%" text-anchor="middle" class="title">${username}</text>
</svg>
`
let avatar = 'assets/anonymous.png'
if(avatarUrl){
avatar = await downloadFileToBuffer(avatarUrl)
}
const image = await sharp(img)
.composite([
{ input: avatar, top: 90, left: 1000 } ,
{ input: Buffer.from(svgUsername), left : 400, top: 540 },
{
input: Buffer.from(quoteSvg),
top: 0,
left: 50,
},
])
.sharpen()
return image.toBuffer()
} catch (error) {
console.log(error);
}
}