Optimise social media images

This commit is contained in:
Jade Ellis 2024-07-23 22:54:46 +01:00
parent f7ce4ebb06
commit 9a227fac71
No known key found for this signature in database
GPG key ID: 8705A2A3EBF77BD2
2 changed files with 13 additions and 8 deletions

View file

@ -12,10 +12,13 @@
// }
$: canonical = SITE_URL + "/blog/" + data.post.canonical;
function calcOgURL(slug: string, date: string, width?: number): URL {
function calcOgURL(slug: string, date: string, ratio?: number, width?: number): URL {
let url = new URL(SITE_URL + "/blog/image");
url.searchParams.set("slug", slug);
url.searchParams.set("date", date);
if (ratio) {
url.searchParams.set("ratio", ratio.toString());
}
if (width) {
url.searchParams.set("width", width.toString());
}
@ -63,7 +66,7 @@
{#if defaultAuthor?.fediverse}
<meta name="fediverse:creator" content={defaultAuthor?.fediverse} />
{/if}
<meta property="og:image" content={calcOgURL(data.post.slug, data.post.date, 1200).toString()} />
<meta property="og:image" content={calcOgURL(data.post.slug, data.post.date, 630/1200, 1200).toString()} />
<meta property="og:image:width" content={(1200).toString()} />
<meta property="og:image:height" content={(1200 / 2).toString()} />
<meta property="og:image:type" content="image/png" />
@ -74,11 +77,11 @@
description={data.post.description}
{canonical}
twitter={{
card: "summary",
card: "summary_large_image",
// site: "@primalmovement",
title: data.post.title,
description: data.post.description,
// image: data.post.image
image: calcOgURL(data.post.slug, data.post.date, 1/2, 1200).toString()}
}}
openGraph={{
title: data.post.title,

View file

@ -19,8 +19,9 @@ const fontData: ArrayBuffer = await fontFile.arrayBuffer();
// const height = 630;
// const width = 1200;
const defaultHeight = 400;
const defaultWidth = 800;
const defaultRatio = 0.5
// const defaultWidth = 800;
const h = (type: any, props: any) => { return { type, props } }
@ -32,10 +33,11 @@ export async function GET({ url }) {
throw error(404, 'Post not found (bad date)')
}
const width = Number(url.searchParams.get('width'))
if (width > 10000) {
const ratio = Number(url.searchParams.get('ratio'))
if (width > 10000 || ratio > 50) {
throw error(400, 'Image too big')
}
if (!cache.has(slug + "/" + dateParts?.join("-") + "/" + width)) {
if (!cache.has(slug + "/" + dateParts?.join("-") + "/" + width + "/" + ratio)) {
// let start = new Date(dateParts[0] || 1, dateParts[1] || 0, dateParts[2] || 0);
// // @ts-ignore
@ -110,7 +112,7 @@ export async function GET({ url }) {
style: 'normal'
}
],
height: defaultHeight,
height: defaultWidth * (ratio || defaultRatio),
width: defaultWidth,
});