Skip to content

Instantly share code, notes, and snippets.

@mrm8488
Created January 9, 2020 04:36
Show Gist options
  • Select an option

  • Save mrm8488/2ff3bc3a462d6f3cd17d5e219e92fecc to your computer and use it in GitHub Desktop.

Select an option

Save mrm8488/2ff3bc3a462d6f3cd17d5e219e92fecc to your computer and use it in GitHub Desktop.
export default function generateSocialImage({
title,
tagline,
+ cloudName,
+ imagePublicID,
+ cloudinaryUrlBase = 'https://res.cloudinary.com',
+ version = null,
titleFont = 'arial',
titleExtraConfig = '',
taglineExtraConfig = '',
taglineFont = 'arial',
imageWidth = 1280,
imageHeight = 669,
textAreaWidth = 760,
textLeftOffset = 480,
titleBottomOffset = 254,
taglineTopOffset = 445,
textColor = '000000',
titleFontSize = 64,
taglineFontSize = 48,
}: Config): string {
// configure social media image dimensions, quality, and format
const imageConfig = [
`w_${imageWidth}`,
`h_${imageHeight}`,
'c_fill',
'q_auto',
'f_auto',
].join(',');
// configure the title text
const titleConfig = [
`w_${textAreaWidth}`,
'c_fit',
`co_rgb:${textColor}`,
'g_south_west',
`x_${textLeftOffset}`,
`y_${titleBottomOffset}`,
`l_text:${titleFont}_${titleFontSize}${titleExtraConfig}:${encodeURIComponent(
title,
)}`,
].join(',');
// configure the tagline text
const taglineConfig = [
`w_${textAreaWidth}`,
'c_fit',
`co_rgb:${textColor}`,
'g_north_west',
`x_${textLeftOffset}`,
`y_${taglineTopOffset}`,
`l_text:${taglineFont}_${taglineFontSize}${taglineExtraConfig}:${encodeURIComponent(
tagline,
)}`,
].join(',');
+ // combine all the pieces required to generate a Cloudinary URL
+ const urlParts = [
+ cloudinaryUrlBase,
+ cloudName,
+ 'image',
+ 'upload',
+ imageConfig,
+ titleConfig,
+ taglineConfig,
+ version,
+ imagePublicID,
+ ];
+
+ // remove any falsy sections of the URL (e.g. an undefined version)
+ const validParts = urlParts.filter(Boolean);
+
+ // join all the parts into a valid URL to the generated image
+ return validParts.join('/');
}
// URL obtained after post the card template to Cloudinary
// https://res.cloudinary.com/jlengstorf/image/upload/v1578253116/lwj/blog-post-card.jpg
const socialImage = getShareImage({
title: 'This Is a Post With an Automatically Generated Social Sharing Card',
tagline: 'Writing blog posts is fun when the robots do some of the work!',
cloudName: 'jlengstorf',
imagePublicID: 'lwj/blog-post-card',
});
console.log(socialImage);
//Not bad! But better customization
const socialImage = getShareImage({
title: 'This Is a Post With an Automatically Generated Social Sharing Card',
tagline: 'Writing blog posts is fun when the robots do some of the work!',
cloudName: 'jlengstorf',
imagePublicID: 'lwj/blog-post-card',
+ titleFont: 'lwj-title.otf',
+ titleExtraConfig: '_line_spacing_-10',
+ taglineFont: 'lwj-tagline.otf',
+ textColor: '232129',
});
console.log(socialImage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment