Open Graph Images
Build an Open Graph card from boxes, text and images with @jimp/layout and JSX, step by step.
An Open Graph image is the card a link shows when it’s shared: a title, maybe a logo and some tags, usually 1200 × 630 pixels.
You could draw one with drawRect and print, but you’d be working out every coordinate yourself, and a longer title would break it.
@jimp/layout lays the card out for you.
You write it as JSX, or as plain objects, made of boxes, text and images in rows and columns like CSS flexbox. render measures the text, wraps it, positions everything and draws it with Jimp.
It’s plain JavaScript with no browser, SVG, React or WebAssembly involved, so it runs anywhere Jimp does: Node.js, browsers, workers and Bun.
This guide builds this card:

Set up
@jimp/layout isn’t part of jimp, so install it alongside:
npm install jimp @jimp/layout To write JSX, point your compiler at @jimp/layout’s JSX runtime. TypeScript, esbuild, Vite and Bun read it from tsconfig.json:
{ "compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "@jimp/layout" }}If the rest of your project uses React, leave tsconfig.json alone and start each card file with this comment instead:
/** @jsxImportSource @jimp/layout */If your tsconfig.json has "jsx": "preserve", as Astro’s does, add /** @jsxRuntime automatic */ above it too.
Node.js can’t run JSX by itself, so compile the file with tsc or your bundler, or run it with a loader such as tsx. If you’d rather not compile anything, every step below also shows the same card as plain objects: pick Objects on any of the tabs.
You also need a font. @jimp/layout draws text with the fonts loadTTF loads (TrueType, OpenType or WOFF) at any size and color, or with the bitmap fonts from loadFont. This guide uses Inter in two weights.
Build the card
-
Start with the background. A card is a
Boxthat fills the image. Give it the padding and the gradient. Text props likefontandcolorset on a box are inherited by all the text inside it, the way CSS inherits them, so set them here once.The
Cardis a component: a function that takes props and returns nodes. The later steps fill it with more components.og-card.tsx import { Jimp } from "jimp";import { loadTTF } from "jimp/load-ttf";import {Box,render,type LayoutChildren,} from "@jimp/layout";const regular = await loadTTF("Inter-Regular.otf");const bold = await loadTTF("Inter-Bold.otf");function Card({children,}: {children?: LayoutChildren;}) {return (<Boxpadding={72}justify="space-between"background={{type: "linear",angle: 135,stops: ["#1b1840", "#3a2d7a"],}}font={regular}color="white">{children}</Box>);}const image = await render(<Card />, {width: 1200,height: 630,Jimp,});await image.write("og-card.png");og-card.ts import { Jimp } from "jimp";import { loadTTF } from "jimp/load-ttf";import {render,type BoxNode,type LayoutNode,} from "@jimp/layout";const regular = await loadTTF("Inter-Regular.otf");const bold = await loadTTF("Inter-Bold.otf");const card = (children: LayoutNode[] = [],): BoxNode => ({type: "box",padding: 72,justify: "space-between",background: {type: "linear",angle: 135,stops: ["#1b1840", "#3a2d7a"],},font: regular,color: "white",children,});const image = await render(card(), {width: 1200,height: 630,Jimp,});await image.write("og-card.png");renderreturns a Jimp image, so you canwriteit, get its bytes withgetBuffer, or keep editing it. The gradient’sangleworks like CSSlinear-gradient:135goes from the top left to the bottom right. Gradients are sized to the box they fill.
-
Add the title and description. A box lays out its children in a column, with
gappixels between them. Text wraps to the width of the column.maxLinescuts a long title short with an ellipsis, so the card never overflows however long the title is:og-card.tsx import { Text } from "@jimp/layout";const post = {title:"Generating Open Graph images " +"with plain JavaScript",description:"Lay out text and images like CSS flexbox, " +"then draw them with Jimp.",site: "jimp-dev.github.io",tags: ["jimp", "layout", "og-images"],};function Body({title,description,}: {title: string;description: string;}) {return (<Box gap={24}><Textfont={bold}fontSize={72}lineHeight={84}maxLines={2}>{title}</Text><Text fontSize={32} color="#c9c4f0">{description}</Text></Box>);}const image = await render(<Card><Bodytitle={post.title}description={post.description}/></Card>,{ width: 1200, height: 630, Jimp },);og-card.ts const post = {title:"Generating Open Graph images " +"with plain JavaScript",description:"Lay out text and images like CSS flexbox, " +"then draw them with Jimp.",site: "jimp-dev.github.io",tags: ["jimp", "layout", "og-images"],};const body = (title: string,description: string,): BoxNode => ({type: "box",gap: 24,children: [{type: "text",text: title,font: bold,fontSize: 72,lineHeight: 84,maxLines: 2,},{type: "text",text: description,fontSize: 32,color: "#c9c4f0",},],});const image = await render(card([body(post.title, post.description)]),{width: 1200,height: 630,Jimp,},);
-
Add a header with an avatar.
direction="row"lays the avatar and the site name side by side, andalign="center"centers them vertically. The image is 64 pixels wide,aspectRatio={1}makes it square,fit="cover"crops it to fill that square, and aradiusof half its width makes it a circle. The card’sjustify="space-between"pushes the header to the top and the body to the bottom:og-card.tsx import { Image } from "@jimp/layout";const avatar = await Jimp.read("avatar.png");function Header({ site }: { site: string }) {return (<Box direction="row" align="center" gap={20}><Imagesrc={avatar}width={64}aspectRatio={1}fit="cover"radius={32}borderWidth={3}borderColor="white"background="white"/><Text fontSize={28} color="#c9c4f0">{site}</Text></Box>);}const image = await render(<Card><Header site={post.site} /><Bodytitle={post.title}description={post.description}/></Card>,{ width: 1200, height: 630, Jimp },);og-card.ts const avatar = await Jimp.read("avatar.png");const header = (site: string): BoxNode => ({type: "box",direction: "row",align: "center",gap: 20,children: [{type: "image",src: avatar,width: 64,aspectRatio: 1,fit: "cover",radius: 32,borderWidth: 3,borderColor: "white",background: "white",},{type: "text",text: site,fontSize: 28,color: "#c9c4f0",},],});const image = await render(card([header(post.site),body(post.title, post.description),]),{ width: 1200, height: 630, Jimp },);
-
Add the tags. Each tag is a box with padding, a
radiusbig enough to make a pill and a softshadow.wraplets a long list of tags flow onto a second line rather than off the card. A third child of the card puts the body in the middle:og-card.tsx function Tag({ label }: { label: string }) {return (<Boxpadding={[10, 22]}radius={999}background="#ffd83a"shadow={{y: 6,blur: 12,color: "rgba(0, 0, 0, 0.35)",}}><Textfont={bold}fontSize={24}color="#1b1840">#{label}</Text></Box>);}function Tags({ tags }: { tags: string[] }) {return (<Box direction="row" wrap gap={12}>{tags.map((label) => (<Tag key={label} label={label} />))}</Box>);}const image = await render(<Card><Header site={post.site} /><Bodytitle={post.title}description={post.description}/><Tags tags={post.tags} /></Card>,{ width: 1200, height: 630, Jimp },);await image.write("og-card.png");og-card.ts const tag = (label: string): BoxNode => ({type: "box",padding: [10, 22],radius: 999,background: "#ffd83a",shadow: {y: 6,blur: 12,color: "rgba(0, 0, 0, 0.35)",},children: [{type: "text",text: `#${label}`,font: bold,fontSize: 24,color: "#1b1840",},],});const tags = (labels: string[]): BoxNode => ({type: "box",direction: "row",wrap: true,gap: 12,children: labels.map(tag),});const image = await render(card([header(post.site),body(post.title, post.description),tags(post.tags),]),{ width: 1200, height: 630, Jimp },);await image.write("og-card.png");
This site’s own Open Graph images are made this way, one per page at build time: see src/og/card.tsx.
Smooth gradients
A card-sized gradient between two dark colors can show faint diagonal bands, because the image only has so many levels between the two colors. How to hide them depends on the format you send:
- PNG: add
dither: trueto the gradient. Each 1200 × 630 card gets a lot bigger, about 75 KB to 512 KB for this one, so only do it when the bands bother you. - JPEG: render as usual, then call
grainwith{ amount: 0.01 }before encoding. JPEG smooths awaydither’s smaller noise. - WebP: call
grainwith{ amount: 0.012, monochrome: false }and encode at quality95. WebP bands in the color more than the brightness, so it needs colored grain.
const card = await render(tree, { width: 1200, height: 630, Jimp });
card.grain({ amount: 0.01 });
const jpeg = await card.getBuffer("image/jpeg", { quality: 85 });Grain is the same every time for the same options, so cached cards don’t change. See Banding for a side-by-side comparison.
About the JSX
The components return plain objects, the same ones the Objects tabs build, so there’s no React, virtual DOM or hooks: <Card> runs Card once and the result goes straight to render.
Inside a Text, children are joined into one string, which is why #{label} works. Inside a Box, arrays from .map() are flattened, and null, false and empty strings are skipped, so {subtitle && <Text>{subtitle}</Text>} works too.
See JSX on the render page for all the rules.
Serve the card
To make cards on demand, wrap the card in one component that takes the post, render it for each request and send the PNG bytes. With the Fetch API’s Response, which works in Node.js, Bun and workers:
function OgCard({ post }: { post: Post }) { return ( <Card> <Header site={post.site} /> <Body title={post.title} description={post.description} /> <Tags tags={post.tags} /> </Card> );}
async function ogImage(post: Post) { const image = await render(<OgCard post={post} />, { width: 1200, height: 630, Jimp, }); const png = await image.getBuffer("image/png");
return new Response(new Uint8Array(png), { headers: { "Content-Type": "image/png", "Cache-Control": "public, max-age=86400", }, });}Here Post is the type of post from step 2: { title: string; description: string; site: string; tags: string[] }.
How the layout works
The layout is a subset of CSS flexbox, written in TypeScript:
- A box lays out its children in a
"column"(the default) or a"row", withgapbetween them andpaddingaround them. Children can have amargin. justifyplaces children along the direction:"start","center","end","space-between","space-around"or"space-evenly".alignplaces them across it:"start","center","end"or"stretch"(the default). A child’salignSelfoverrides its parent’salign.widthandheightare pixels, percentages of the parent like"50%", or"auto"to fit the content, andaspectRatiogives one from the other.growshares out spare space andshrinktakes away space that’s missing, but not below a node’s content: text doesn’t get narrower than its longest word.wrapstarts a new line for children that don’t fit, for rows of tags.position: "absolute"takes a node out of the row or column and places it withtop,right,bottomandleft, for badges and background images.- Text is measured with
measureTextandmeasureTextHeight, and wrapped the same wayprintwraps it.
See render for every prop and how they differ from CSS.
See also
render: every node type and prop, andlayoutto get positions without drawing.- Text and fonts: loading fonts with
loadTTFandloadFont. - Drawing: the shapes and gradients
@jimp/layoutdraws with. - Using in Browser: rendering cards in the browser or a worker.