substr/magick.ts
2024-10-24 14:28:49 +02:00

62 lines
1.8 KiB
TypeScript

import Profile from "./models/profile.ts";
import { checkIfFileExists, runCommand } from "./utils.ts";
import { log } from "./log.ts";
const tmpImgDir = "/tmp/substr/img";
function createRoundedImage(profile: Profile) {
const command = [
'magick',
profile.picture,
'-resize', '256x256',
'(', '+clone', '-alpha', 'extract',
'-draw', "fill black polygon 0,0 0,128 128,0 fill white circle 128,128 128,0",
'(', '+clone', '-flip', ')', '-compose', 'Multiply', '-composite',
'(', '+clone', '-flop', ')', '-compose', 'Multiply', '-composite',
')',
'-alpha', 'off',
'-compose', 'CopyOpacity',
'-composite',
`${tmpImgDir}/p-${profile.event.id}-rounded.png`
];
return runCommand(command);
}
async function createOgImage(profile: Profile, ogImagePath: string, backgroundColor: string) {
const status = await createRoundedImage(profile);
if (status.success) {
const command = [
'magick',
`${tmpImgDir}/p-${profile.event.id}-rounded.png`,
'-resize', '256x256',
'-background', backgroundColor,
'-gravity', 'center',
'-extent', '1200x630',
'-size', '1200x630',
"-format", "png",
ogImagePath
];
return runCommand(command);
}
};
export async function generateOgProfileImage(profile: Profile) {
if (!profile.picture) return false;
const ogImagePath = `${tmpImgDir}/og-p-${profile.event.id}.png`;
const backgroundColor = "#333333";
const fileExists = await checkIfFileExists(ogImagePath);
if (!fileExists) {
const status = await createOgImage(profile, ogImagePath, backgroundColor);
if (status.success) {
log(`Created OG image for ${profile.username}: ${ogImagePath}`, "blue")
} else {
log(`Could not create OG image for ${profile.username}`, "yellow")
}
}
}