Skip to content
Hokusai2.2.2
ivantokar.com

Social card

Goal. Turn a photo and a headline into the 1200 × 630 image that chat apps and social networks show for a link. Inputs: scene.png and phone.jpg. Needs: Hokusai 2.2.2 with text rendering (capabilities().textRendering).

// 1200 × 630 is the usual size for link previews.
func socialCard(from photo: URL, title: String) throws -> Hokusai {
var style = TextStyle(font: "sans Bold", fontSize: 64, color: .white)
style.shadow = TextShadow(offsetX: 3, offsetY: 3, blur: 4, color: Color(red: 0, green: 0, blue: 0, opacity: 0.75))
return try Hokusai(url: photo)
.autoOrient()
.resize(width: 1200, height: 630, fit: .cover, position: .attention)
.drawText(.plain(title), placement: .gravity(.southWest, offsetX: 56, offsetY: 48),
layout: .width(900), style: style)
}
let card = try socialCard(from: URL(fileURLWithPath: "scene.png"), title: "Keeping the light: a year at Pharos Point")
try await card.webp(quality: 82).write(to: URL(fileURLWithPath: "card.webp"))
try await card.jpeg(quality: 85).write(to: URL(fileURLWithPath: "card.jpg")) // fallback for crawlers
// Variation: the same recipe from a phone photo, which needs autoOrient.
try await socialCard(from: URL(fileURLWithPath: "phone.jpg"), title: "From a phone, upright")
.webp(quality: 82).write(to: URL(fileURLWithPath: "card-from-phone.webp"))
  • The landscape cropped to 1200 by 630 with the title Keeping the light, a year at Pharos Point, in white at the lower left.
    card.webpWEBP · 1200 × 630 · 26 KB
  • The same card as a JPEG for crawlers that do not read WebP.
    card.jpg (fallback)JPEG · 1200 × 630 · 62 KB
  • The card made from the sideways phone photo: upright, with a shorter title.
    from a phone photoWEBP · 1200 × 630 · 21 KB
  1. autoOrient() makes a phone photo upright before anything measures it, so the same function works for any upload (why).
  2. resize(width: 1200, height: 630, fit: .cover, position: .attention) fills the card exactly and crops to the interesting part: the lighthouse stays in frame even though it is off-centre (position).
  3. drawText(…) places the title with .gravity(.southWest, offsetX:, offsetY:) so it stays 56 px from the left and 48 px from the bottom whatever the card size. layout: .width(900) wraps long titles; the shadow keeps white text legible over any sky (text).
  4. webp(quality: 82) for the web, and JPEG as a fallback for crawlers.
  • Longer titles: .width(900) wraps at 900 px; lower fontSize or use .fit(width: 900, height: 200) to guarantee the text fits a box.
  • Different aspect ratios (1:1, 1.91:1): change only the resize box.
  • A photo with a dark sea and a bright sky: keep the shadow, or composite a darkening .multiply layer under the text (blend modes).
  • Custom fonts: TextStyle(fontFile:) when the host does not have your font installed.