Skip to content
This repository was archived by the owner on Sep 27, 2018. It is now read-only.

Commit 6e1f8aa

Browse files
author
GSI2013
committed
Wrote Jekyll tag that renders base64 codes of images fetched from the web
0 parents  commit 6e1f8aa

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed

README.textile

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
h1. Jekyll Image Encode
2+
3+
This Jekyll plugin fetches images from the web and renders their according base64 codes.
4+
5+
Be sure to know your reasons when using it.
6+
7+
8+
h2. Installation
9+
10+
Set the variable @PATH_TO_JEKYLL_SITE@ correctly and run these commands accordingly:
11+
12+
pre. echo "gem 'jekyll_image_encode'" >> $PATH_TO_JEKYLL_SITE/Gemfile
13+
bundle
14+
echo "require 'jekyll_image_encode'" >> $PATH_TO_JEKYLL_SITE/_plugins/ext.rb
15+
16+
17+
h2. Usage
18+
19+
In the source attribute of an HTML *img* element, call the *base64-tag* providing the image URL as the only parameter:
20+
21+
pre. <img src="{% base64 http://example.org/image.png %}" />

jekyll_image_encode.gemspec

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
Gem::Specification.new do |s|
2+
s.name = 'jekyll_image_encode'
3+
s.version = '0.0.1'
4+
s.date = '2013-08-10'
5+
s.summary = "Jekyll Image Encode"
6+
s.description = "Jekyll tag that renders base64 codes of images fetched from the web"
7+
s.authors = ["GSI"]
8+
s.email = '[email protected]'
9+
s.files = Dir.glob('lib/**/*') # `git ls-files`.split($/)
10+
s.homepage = 'https://github.com/GSI/' + s.name
11+
s.license = 'MIT'
12+
end

lib/jekyll_image_encode.rb

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
module ImageEncodeCache
2+
@@cached_base64_codes = Hash.new
3+
4+
def cached_base64_codes
5+
@@cached_base64_codes
6+
end
7+
8+
def cached_base64_codes= val
9+
@@cached_base64_codes = val
10+
end
11+
end
12+
13+
module Jekyll
14+
module Tags
15+
class ImageEncodeTag < Liquid::Tag
16+
include ImageEncodeCache
17+
18+
def initialize(tag_name, url, options)
19+
@url = url.strip
20+
super
21+
end
22+
23+
def render(context)
24+
encode_image
25+
end
26+
27+
def encode_image
28+
require 'open-uri'
29+
require 'base64'
30+
31+
encoded_image = ''
32+
33+
if self.cached_base64_codes.has_key? @url
34+
encoded_image = self.cached_base64_codes[@url]
35+
else
36+
# p "Caching #{@url} as local base64 string ..."
37+
open(@url) do |image|
38+
encoded_image = Base64.encode64(image.read)
39+
end
40+
self.cached_base64_codes.merge!(@url => encoded_image)
41+
end
42+
43+
"data:image;base64, #{encoded_image}"
44+
end
45+
end
46+
end
47+
end
48+
49+
Liquid::Template.register_tag('base64', Jekyll::Tags::ImageEncodeTag)

0 commit comments

Comments
 (0)