From 17e922b8c5705a9f693cd7474077c4684498a578 Mon Sep 17 00:00:00 2001 From: Stephen Tse Date: Sat, 26 Apr 2025 19:26:37 -0700 Subject: [PATCH] Fixed custom OG image using old extension --- quartz/plugins/emitters/ogImage.tsx | 13 +++++++++++++ quartz/util/url.ts | 13 +++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 quartz/util/url.ts diff --git a/quartz/plugins/emitters/ogImage.tsx b/quartz/plugins/emitters/ogImage.tsx index d7a6ef720..faf77c317 100644 --- a/quartz/plugins/emitters/ogImage.tsx +++ b/quartz/plugins/emitters/ogImage.tsx @@ -12,6 +12,8 @@ import { BuildCtx } from "../../util/ctx" import { QuartzPluginData } from "../vfile" import fs from "node:fs/promises" import chalk from "chalk" +import { getExtFromUrl } from "../../util/url" +import { imageExtsToOptimize, targetOptimizedImageExt } from "./assets" const defaultOptions: SocialImageOptions = { colorScheme: "lightMode", @@ -151,6 +153,17 @@ export const CustomOgImages: QuartzEmitterPlugin> = userDefinedOgImagePath = isAbsoluteURL(userDefinedOgImagePath) ? userDefinedOgImagePath : `https://${baseUrl}/static/${userDefinedOgImagePath}` + + // Replace extension of eligible image files with target extension if image optimization is enabled. + if (ctx.cfg.configuration.optimizeImages) { + const ext = getExtFromUrl(userDefinedOgImagePath)?.toLowerCase() + if (ext && imageExtsToOptimize.has(ext)) { + userDefinedOgImagePath = userDefinedOgImagePath.replace( + ext, + targetOptimizedImageExt, + ) + } + } } const generatedOgImagePath = isRealFile diff --git a/quartz/util/url.ts b/quartz/util/url.ts new file mode 100644 index 000000000..ed0e16be1 --- /dev/null +++ b/quartz/util/url.ts @@ -0,0 +1,13 @@ +/** + * Extracts file extension from a file resource URL. + * + * @param url - URL to extract the file extension from + * @returns The file extension (with a preceding dot) or undefined if none found + */ +export function getExtFromUrl(url: string): string | undefined { + const urlObj = new URL(url) + const pathname = urlObj.pathname + // Remove any query parameters or hash first + const ext = pathname.split(/[#?]/)[0].split(".").pop()?.trim() + return ext === pathname ? undefined : "." + ext +}