-
Notifications
You must be signed in to change notification settings - Fork 13
/
jekyll-art-gallery-generator.rb
353 lines (319 loc) · 14.5 KB
/
jekyll-art-gallery-generator.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# Jekyll art gallery generator plugin
# Distribiuted under MIT license with attribution
# sourced from https://github.com/ggreer/jekyll-gallery-generator
#
require 'rmagick'
include Magick
include FileUtils
$image_extensions = [".png", ".jpg", ".jpeg", ".gif"]
module Jekyll
class GalleryFile < StaticFile
def write(dest)
return false
end
end
class ReadYamlPage < Page
def read_yaml(base, name, opts = {})
begin
self.content = File.read(File.join(base.to_s, name.to_s), (site ? site.file_read_opts : {}).merge(opts))
if content =~ /\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)/m
self.content = $POSTMATCH
self.data = SafeYAML.load($1)
end
rescue SyntaxError => e
Jekyll.logger.warn "YAML Exception reading #{File.join(base, name)}: #{e.message}"
rescue Exception => e
Jekyll.logger.warn "Error reading file #{File.join(base, name)}: #{e.message}"
end
self.data ||= {}
end
end
# main page linking all galleries together
class GalleryIndex < ReadYamlPage
def initialize(site, base, dir, galleries)
@site = site
@base = base
@dir = dir.gsub(/^_/, "")
@name = "index.html"
# load gallery configs from the _data/gallery.yml file
config = site.data["gallery"] || {}
self.process(@name)
gallery_index = File.join(base, "_layouts", "art_gallery_index.html")
unless File.exists?(gallery_index)
gallery_index = File.join(File.dirname(__FILE__), "art_gallery_index.html")
end
self.read_yaml(File.dirname(gallery_index), File.basename(gallery_index))
self.data["title"] = config["title"] || "Photos"
self.data["galleries"] = []
begin
sort_field = config["sort_field"] || "name"
galleries.sort! {|a,b| a.data[sort_field] <=> b.data[sort_field]}
rescue Exception => e
puts "Error sorting galleries: #{e}"
puts e.backtrace
end
if config["sort_reverse"]
galleries.reverse!
end
site.data["galleries-sorted"]=[]
galleries.each {|gallery|
unless gallery.hidden
self.data["galleries"].push(gallery.data)
# site-wide data for use in liquid templates
# available to liquid via site.data.gallery.galleries.[name]. subitems are manually defined in gallery.yml, and title, link, description, best_image etc and images array
# inject additional auto-discovered data back into sitewide gallery object
gallery_title=gallery.data["title"]
if site.data["gallery"]["galleries"].has_key?(gallery_title)
site.data["gallery"]["galleries"][gallery_title].merge!(gallery.data)
else
site.data["gallery"]["galleries"][gallery_title]=gallery.data
end
site.data["navigation"].push({"title"=> gallery.data["title"], "url"=> gallery.data["link"], "side"=> "left"})
site.data["galleries-sorted"].push(gallery.data["title"]) # sorted array to order the galleries hash on the portfolio page
end
}
end
end
# gallery page for each gallery
class GalleryPage < ReadYamlPage
attr_reader :hidden
def initialize(site, base, dir, gallery_name)
@site = site
@base = base
#source_dir=dir
@dir = dir.gsub(/^_/, "").gsub(/[^0-9A-Za-z.\\\-\/]/, '_').downcase # destination dir, same as source without the leading underscore. web compatible
FileUtils.mkdir_p(site.in_dest_dir(@dir), :mode => 0755)
@name = "index.html"
@images = []
@hidden = false
# load configs, set defaults
config = site.data["gallery"] || {}
symlink = config["symlink"] || false
# downcase gallery names, technically duplicating them
galleries = {}
(config["galleries"] || {}).each_pair do |k,v|
galleries.merge!({k.downcase => v})
end
gallery_config = galleries[gallery_name.downcase] || {}
#puts "Generating #{gallery_name}: #{gallery_config}"
sort_field = config["sort_field"] || "name"
self.process(@name)
gallery_page = File.join(base, "_layouts", "art_gallery_page.html")
unless File.exists?(gallery_page)
gallery_page = File.join(File.dirname(__FILE__), "art_gallery_page.html")
end
self.read_yaml(File.dirname(gallery_page), File.basename(gallery_page))
self.data["gallery"] = gallery_name # aka folder name
self.data["description"] = gallery_config["description"]
# prettify gallery name if not set
gallery_name = gallery_name.gsub("_", " ").gsub(/\w+/) {|word| word.capitalize}
gallery_name = gallery_config["title"] || gallery_name
self.data["title"] = gallery_name
self.data["link"] = "/#{@dir}/"
# thumbnail destination
scale_method = gallery_config["scale_method"] || config["scale_method"] || "fit" # each gallery can have it's own scale method, or use the global scale if defined
@hidden = gallery_config["hidden"] || false # the gallery can also be hidden by renaming it to start with a dot
if @hidden
self.data["sitemap"] = false
return
end
if config["watermark"] # load watermark image
wm_img = Image.read(File.join(base, "images",config["watermark"])).first
end
# process and copy images
self.data["captions"] = {}
date_times = {}
Dir.foreach(dir) do |image|
next if image.chars.first == "."
next unless image.downcase().end_with?(*$image_extensions)
image_path = File.join(dir, image) # source image short path
# img_src = site.in_source_dir(image_path) # absolute path for the source image
# extract timestamp
if sort_field == "timestamp"
begin
#date_times[image] = EXIFR::JPEG.new(image_path).date_time.to_i
date_times[image]=0
# ["DateTime"], ["DateTimeDigitized"], ["DateTimeOriginal"]
date_array = ImageList.new(image_path).get_exif_by_entry("DateTime")
if date_array != nil && date_array.length > 0 and date_array[0].length > 1
date_times[image]=DateTime.strptime(date_array[0][1],"%Y:%m:%d %H:%M:%S").to_time.to_i
end
# puts "gtot #{date_array} date" + date_times[image].to_s
rescue Exception => e
puts "Error getting date_time "+date_times[image]+" for #{image}: #{e}"
end
end
# cleanup, watermark and copy the files
# Strip out the non-ascii character and downcase the final file name
dest_image=image.gsub(/[^0-9A-Za-z.\-]/, '_').downcase
dest_image_abs_path = site.in_dest_dir(File.join(@dir, dest_image))
if File.file?(dest_image_abs_path) == false or File.mtime(image_path) > File.mtime(dest_image_abs_path)
if config["strip_exif"] or config["watermark"] or config["size_limit"] # can't simply copy or symlink, need to pre-process the image
source_img=ImageList.new(image_path)
print "Generating #{dest_image}..."
if config["strip_exif"]
print "stripping EXIF..."
source_img.strip!
end
if config["watermark"]
if [source_img.columns,source_img.rows].min < 600
print "too small to watermark"
else
print "watermarking"
# watermark parameters are: image, how much of watermark lightness to compose in "xx%", how much of watermark's saturation to compose (%), gravity (SouthEastGravity is good), x-offset (origin depends on gravity), y-offset
source_img.composite!(wm_img,Magick::SouthEastGravity,20,20,Magick::HardLightCompositeOp).write(dest_image_abs_path)
end
end
if config["size_limit"]
source_img.resize_to_fit!(config["size_limit"], config["size_limit"]) if (source_img.columns > config["size_limit"] || source_img.rows > config["size_limit"]) # resize only if bigger than the limit
end
source_img.write(dest_image_abs_path)
print "\n"
elsif symlink
print "Symlinking #{image_path} to #{dest_image}..."
link_src = site.in_source_dir(image_path)
link_dest = dest_image_abs_path
@site.static_files.delete_if { |sf|
sf.relative_path == "/" + image_path
}
@site.static_files << GalleryFile.new(site, base, dir, image)
if File.exists?(link_dest) or File.symlink?(link_dest)
if not File.symlink?(link_dest)
puts "#{link_dest} exists but is not a symlink. Deleting."
File.delete(link_dest)
elsif File.readlink(link_dest) != link_src
puts "#{link_dest} points to the wrong file. Deleting."
File.delete(link_dest)
end
end
if not File.exists?(link_dest) and not File.symlink?(link_dest)
File.symlink(link_src, link_dest)
end
print "\n"
else
puts "Copying #{image_path} to #{dest_image}..."
FileUtils.cp(image_path,dest_image_abs_path)
end
end
# Add file descriptions if defined
if gallery_config.has_key?(image)
# puts "added ${image} = #{gallery_config[image]}"
self.data["captions"][dest_image]=gallery_config[image]
else
# If not defined add a trimmed filename to help with SEO
self.data["captions"][dest_image]=File.basename(image,File.extname(image)).gsub("_", " ")
end
# remember the image
@images.push(dest_image)
@site.static_files << GalleryFile.new(site, base, @dir, dest_image)
# make a thumbnail
makeThumb(image_path, dest_image, config["thumbnail_size"]["x"] || 400, config["thumbnail_size"]["y"] || 400, scale_method)
#@site.static_files << GalleryFile.new(site, base, File.join(@dir, "thumbs"), dest_image)
end
# sort pictures inside the gallery
begin
if sort_field == "timestamp"
@images.sort! {|a,b|
if date_times[a] == date_times[b]
a <=> b # do the name if the timestamps match
else
date_times[a] <=> date_times[b]
end
}
else
@images.sort!
end
if gallery_config["sort_reverse"]
@images.reverse!
end
rescue Exception => e
puts "Error sorting images in gallery #{gallery_name}: #{e}"
# puts e.backtrace
end
site.static_files = @site.static_files
self.data["images"] = @images
best_image = gallery_config["best_image"] || @images[0]
best_image.gsub!(/[^0-9A-Za-z.\-]/, '_') # renormalize the name - important in case the best image name is specified via config
best_image.downcase! # two step because mutating gsub returns nil that's unusable in a compound call
#best_image = File.join(@dir, best_image)
self.data["best_image"] = best_image
# generate best image thumb for the gallery super-index page
makeThumb(site.in_dest_dir(File.join(@dir, best_image)), "front_"+best_image, config["front_thumb_size"]["x"] || 400, config["front_thumb_size"]["y"] || 400,"crop")
# generate best image thumb for the header of a gallery index page
makeThumb(site.in_dest_dir(File.join(@dir, best_image)), "header_"+best_image, config["header_thumb_size"]["x"] || 400, config["header_thumb_size"]["y"] || 400,"crop")
self.data["header"]["image_fullwidth"] = "thumbs/header_"+best_image # used in the theme
GC.start
end
def makeThumb(image_path, dest_image, thumb_x, thumb_y, scale_method)
# create thumbnail if it is not there
thumbs_dir = File.join(site.dest, @dir, "thumbs")
#thumbs_dir = File.join(@dir, "thumbs")
thumb_path = File.join(thumbs_dir, dest_image)
# create thumbnails
FileUtils.mkdir_p(thumbs_dir, :mode => 0755)
if File.file?(thumb_path) == false or File.mtime(image_path) > File.mtime(thumb_path)
begin
m_image = ImageList.new(image_path)
# m_image.auto_orient!
#m_image.send("resize_to_#{scale_method}!", max_size_x, max_size_y)
if scale_method == "crop"
m_image.resize_to_fill!(thumb_x, thumb_y)
elsif scale_method == "crop_bottom"
m_image.resize_to_fill!(thumb_x, thumb_y, NorthGravity)
elsif scale_method == "crop_right"
m_image.resize_to_fill!(thumb_x, thumb_y, WestGravity)
elsif scale_method == "crop_left"
m_image.resize_to_fill!(thumb_x, thumb_y, EastGravity)
elsif scale_method == "crop_top"
m_image.resize_to_fill!(thumb_x, thumb_y, SouthGravity)
else
m_image.resize_to_fit!(thumb_x, thumb_y)
end
# strip EXIF from thumbnails. Some browsers, notably, Safari on iOS will try to rotate images according to the 'orientation' tag which is no longer valid in case of thumbnails
m_image.strip!
puts "Writing thumbnail to #{thumb_path}"
m_image.write(thumb_path)
rescue Exception => e
puts "Error generating thumbnail for #{image_path}: #{e}"
# puts e.backtrace
end
end
# record the thumbnail
@site.static_files << GalleryFile.new(@site, @base, thumbs_dir, dest_image)
end
end
class GalleryGenerator < Generator
safe true
def generate(site)
config = site.data["gallery"] || {}
dir = config["source_dir"] || "_photos"
galleries = []
original_dir = Dir.getwd
# generate galleries
Dir.chdir(site.source)
begin
Dir.foreach(dir) do |gallery_dir|
gallery_path = File.join(dir, gallery_dir)
if File.directory?(gallery_path) and gallery_dir.chars.first != "." # skip galleries starting with a dot
gallery = GalleryPage.new(site, site.source, gallery_path, gallery_dir)
gallery.render(site.layouts, site.site_payload)
gallery.write(site.dest)
site.pages << gallery
galleries << gallery
end
end
rescue Exception => e
puts "Error generating galleries: #{e}"
puts e.backtrace
end
Dir.chdir(original_dir)
# fix bug
site.data["navigation"] = []
# generate gallery index
gallery_index = GalleryIndex.new(site, site.source, dir, galleries)
gallery_index.render(site.layouts, site.site_payload)
gallery_index.write(site.dest)
site.pages << gallery_index
end
end
end