Created
June 20, 2019 00:49
-
-
Save fallwith/5691fecd1f359a8c8c80b38a1d782df3 to your computer and use it in GitHub Desktop.
View - a simple terminal image viewer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# frozen_string_literal: true | |
require 'base64' | |
# | |
# View is a simple terminal image viewer | |
# | |
# NOTE: currently only iTerm is supported | |
# | |
# Instructions: | |
# * Save this file as view.rb | |
# * Make this file executable: 'chmod 755 view.rb' | |
# * View image files: './view.rb <image1> <image2> <image3>' | |
class View | |
def initialize(paths) | |
@paths = paths | |
validate_paths | |
validate_terminal | |
end | |
def render | |
@paths.each { |p| render_path(p) } | |
end | |
private | |
def render_path(path) | |
data = Base64.encode64(File.open(path, 'rb').read) | |
puts "\033]1337;File=size=#{data.size};inline=1:#{data}\a\n\n" | |
end | |
def validate_paths | |
usage('No image paths given') if @paths.empty? | |
@paths.each do |path| | |
unless File.exist?(path) && File.file?(path) && File.readable?(path) | |
usage("Path '#{path}' does not appear to be a valid image path") | |
end | |
end | |
end | |
def validate_terminal | |
usage('Please run this tool within iTerm') \ | |
if ENV['TERM_PROGRAM'] != 'iTerm.app' | |
end | |
def usage(error_msg = nil) | |
puts "\n #{error_msg}\n\n" if error_msg | |
puts "Usage: #{$PROGRAM_NAME} </path/to/image/file1> <file2> <file3>" | |
exit | |
end | |
end | |
View.new(ARGV).render if $PROGRAM_NAME == __FILE__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment