Skip to content

Instantly share code, notes, and snippets.

@tayiorbeii
Created June 7, 2023 16:34
Show Gist options
  • Save tayiorbeii/fb6f74604ea5600c95b387f63220b092 to your computer and use it in GitHub Desktop.
Save tayiorbeii/fb6f74604ea5600c95b387f63220b092 to your computer and use it in GitHub Desktop.
/*
# OG Image Downloader
- Retrieves the open graph image (og:image) from the currently active browser tab
- Resizes the image to a width of 600 pixels, maintaining aspect ratio
- Saves the resized image in the Downloads folder with a derived name
- If no og:image tag is found, displays an error message and exits
*/
//Author: Taylor Bell
//Name: OG Image Downloader
//Description: Downloads and resizes the open graph image (og:image) from a web page
import "@johnlindquist/kit"
import ogs from 'open-graph-scraper';
import sharp from 'sharp'
let tab = await getActiveTab()
let options = { url: tab }
let data = await ogs(options)
let url = data?.result?.ogImage[0]?.url
if (!url) {
await div(`No og:image found for ${tab}`)
await wait(1000)
exit()
}
let imageName = tab.split("/").pop()
if (!imageName)
imageName = tab.split("//").pop().replace("/", "")
if (!imageName.endsWith(".png"))
imageName = `${imageName}.png`
console.log({ imageName })
let dest = home("Downloads", imageName)
let buffer = await download(url)
let width = 600
let metadata = await sharp(buffer).metadata()
let newHeight = Math.floor(
metadata.height * (width / metadata.width)
)
await sharp(buffer)
.resize(width, newHeight)
.toFile(dest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment