Skip to content

Commit 486b76d

Browse files
committed
feat: add SocialImage component for dynamic Open Graph image generation in Layout.astro
1 parent 10df189 commit 486b76d

File tree

2 files changed

+59
-6
lines changed

2 files changed

+59
-6
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
---
2+
// This component creates a properly sized open graph image for social media
3+
// It maintains the aspect ratio of the image while placing it within
4+
// the recommended 1200x630 container for social sharing
5+
6+
import { Image } from "astro:assets";
7+
import type { ImageMetadata } from "astro";
8+
9+
interface Props {
10+
image: ImageMetadata;
11+
alt: string;
12+
}
13+
14+
const { image, alt } = Astro.props;
15+
16+
// Social media preview dimensions (1200x630 is standard for FB/Twitter)
17+
const WIDTH = 1200;
18+
const HEIGHT = 630;
19+
---
20+
21+
<div
22+
class="social-image-wrapper"
23+
style={`width: ${WIDTH}px; height: ${HEIGHT}px;`}
24+
>
25+
<Image
26+
src={image}
27+
alt={alt}
28+
width={WIDTH}
29+
height={HEIGHT}
30+
style="object-fit: contain; width: 100%; height: 100%;"
31+
/>
32+
</div>
33+
34+
<style>
35+
.social-image-wrapper {
36+
display: flex;
37+
align-items: center;
38+
justify-content: center;
39+
background-color: #121620; /* Match your site's background color */
40+
position: relative;
41+
overflow: hidden;
42+
}
43+
</style>

src/src/layouts/Layout.astro

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22
import "../styles/global.css";
33
import { ViewTransitions } from "astro:transitions";
44
import OwlImage from "../assets/Owl-medium.jpg";
5+
import { getImage } from "astro:assets";
6+
import SocialImage from "../components/SocialImage.astro";
57
68
interface Props {
79
title?: string;
810
description?: string;
9-
ogImage?: string | ImageMetadata;
11+
ogImage?: ImageMetadata;
1012
canonicalURL?: URL | string;
1113
}
1214
@@ -17,11 +19,19 @@ const {
1719
canonicalURL = Astro.url,
1820
} = Astro.props;
1921
20-
// Get the full URL for og:image regardless of whether it's a relative or absolute path
21-
const ogImageURL =
22-
typeof ogImage === "string"
23-
? new URL(ogImage, Astro.site || Astro.url).href
24-
: new URL(ogImage.src, Astro.site || Astro.url).href;
22+
// Generate the social image
23+
const socialImage = await getImage({
24+
src: SocialImage,
25+
width: 1200,
26+
height: 630,
27+
props: {
28+
image: ogImage,
29+
alt: "OutwardLight Studio - Open Source Development",
30+
},
31+
});
32+
33+
// Use the generated social image URL
34+
const ogImageURL = socialImage.src;
2535
---
2636

2737
<!doctype html>

0 commit comments

Comments
 (0)