substr/magick.ts

68 lines
2.0 KiB
TypeScript

import Profile from "./models/profile.ts";
import { checkFileExists, getImageMagickCommand, runCommand } from "./utils.ts";
import { log } from "./log.ts";
const tmpImgDir = "/tmp/substr/img";
const magick = await getImageMagickCommand();
if (!magick) {
log("ImageMagick is not installed. Cannot generate preview images", "yellow")
}
function createRoundedImage(profile: Profile) {
if (!magick || !profile.picture) return false;
const args = [
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(magick, args);
}
async function createOgImage(profile: Profile, ogImagePath: string, backgroundColor: string) {
if (!magick) return false;
const status = await createRoundedImage(profile);
if (status && status.success) {
const args = [
`${tmpImgDir}/p-${profile.event.id}-rounded.png`,
'-resize', '256x256',
'-background', backgroundColor,
'-gravity', 'center',
'-extent', '1200x630',
'-size', '1200x630',
"-format", "png",
ogImagePath
];
return runCommand(magick, args);
}
};
export async function generateOgProfileImage(profile: Profile) {
if (!magick || !profile.picture) return false;
const ogImagePath = `${tmpImgDir}/og-p-${profile.event.id}.png`;
const backgroundColor = "#333333";
const fileExists = await checkFileExists(ogImagePath);
if (!fileExists) {
const status = await createOgImage(profile, ogImagePath, backgroundColor);
if (status && status.success) {
log(`Created OG image for ${profile.username}: ${ogImagePath}`, "blue")
} else {
log(`Could not create OG image for ${profile.username}`, "yellow")
}
}
}