Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Local Images #36

Open
KiwiKilian opened this issue Jan 1, 2023 · 3 comments
Open

Local Images #36

KiwiKilian opened this issue Jan 1, 2023 · 3 comments

Comments

@KiwiKilian
Copy link
Owner

How to use local/relative images inside OG image template?

@KiwiKilian
Copy link
Owner Author

KiwiKilian commented Feb 20, 2023

For now I'm using a shortcode to inline images:

import { promises as fs } from 'node:fs';
import path from 'node:path';

eleventyConfig.addNunjucksAsyncShortcode('inlineImage', async (imagePath) => {
  const base64Image = await fs.readFile(path.join(this.eleventy.directories.input, imagePath), 'base64');

  return `data:image/jpeg;base64,${base64Image}`;
});

Inside og-image.og.njk:

<img width="352" height="440" src="{% inlineImage "assets/images/some-image.jpeg" %}" />

@what1s1ove
Copy link

what1s1ove commented Jun 6, 2024

Hi there!

Here is a slightly updated example to cover more image formats:

import { promises as fs } from 'node:fs'
import path from 'node:path'

config.addNunjucksAsyncShortcode(
`inlineImage`,
async (path) => {
  let extension = path.extname(path).slice(1)
  let imgPath = path.join(config.dir.input, path)
  let base64Image = await fs.readFile(imgPath, `base64`)

  if (extension === `svg`) {
  extension = `svg+xml`
  }
  
  return `data:image/${extension};base64,${base64Image}`
},
)

But it is still not perfect. It is better to use a library like file-type (https://www.npmjs.com/package/file-type) to cover more cases.

Also, I think it would be good if this plugin itself provided additional shortcodes/filters, like the official RSS plugin does: https://www.11ty.dev/docs/plugins/rss/#supplies-the-following-nunjucks-filters

@KiwiKilian
Copy link
Owner Author

Thanks for sharing, was also thinking to add this one day to the plugin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants