diff --git a/lib/thumbnail/creation.rb b/lib/thumbnail/creation.rb new file mode 100644 index 0000000000000000000000000000000000000000..039ae4547e97b7dc08f42f0dd5f3899fd0807d79 --- /dev/null +++ b/lib/thumbnail/creation.rb @@ -0,0 +1,68 @@ +module Thumbnail + module Creation + + include Formats + + def generate_thumbnail(input, filename, size) + unless accepted_formats.include? File.extname(filename) + return default_thumbnail + else + thumbnail = thumbnail_path(filename, size) + output = "#{root_dir}#{thumbnail}" + begin + if accepted_video_formats.include? File.extname(input) + generate_video_thumbnail(input, output, size) + else + generate_image_thumbnail(input, output, size) + end + rescue + return default_thumbnail + else + return thumbnail + end + end + + end + + private + + def generate_video_thumbnail(input,output,size) + movie = FFMPEG::Movie.new(input) + frame = (movie.duration * 25/100).floor + movie.screenshot(output, + { seek_time: frame, resolution: size }, + preserve_aspect_ratio: :width) + end + + def generate_image_thumbnail(input,output,size) + # Read the image and resize it. The `change_geometry' method + # computes the new image geometry and yields to a block. The + # return value of the block is the return value of the method. + img = Magick::Image.read(input)[0] + img.change_geometry!(size) { |cols, rows| img.thumbnail! cols, rows } + img.write(output) + end + + def encode_hash_from(object) + Digest::SHA1.hexdigest object + end + + def thumbnail_path(filename, size) + thumbnail_name = encode_hash_from filename + thumbnail_path = "#{thumbnails_dir}/#{thumbnail_name}_#{size}.jpg" + end + + def default_thumbnail + @default_thumbnail ||= "#{thumbnails_dir}/default_thumbnail.jpg" + end + + def thumbnails_dir + @thumbnails_dir ||= "/thumbnails" + end + + def root_dir + @root_dir ||= Rails.root.join('public') + end + + end +end diff --git a/lib/thumbnail/formats.rb b/lib/thumbnail/formats.rb new file mode 100644 index 0000000000000000000000000000000000000000..c34ef649707ef84ebb390693f83e0dd7f378ffc4 --- /dev/null +++ b/lib/thumbnail/formats.rb @@ -0,0 +1,27 @@ +module Thumbnail + module Formats + + def accepted_video_formats + lower = [".mp4", ".wmv", ".3gp", ".asf", ".avi", ".flv", ".mov", ".mpg", ".mpeg", ".rmvb", ".vob", ".webm"] + upper = [".MP4", ".WMV", ".3GP", ".ASF", ".AVI", ".FLV", ".MOV", ".MPG", ".MPEG", ".RMVB", ".VOB", ".WEBM"] + return lower + upper + end + + def accepted_image_formats + lower = [".jpg", ".jpeg", ".gif", ".png", ".bmp", ".tif"] + upper = [".JPG", ".JPEG", ".GIF", ".PNG", ".BMP", ".TIF"] + return lower + upper + end + + def accepted_other_formats + lower = [".pdf", ".pps"] + upper = [".PDF", ".PPS"] + return lower + upper + end + + def accepted_formats + return accepted_video_formats + accepted_image_formats + accepted_other_formats + end + + end +end