LoginSignup
17
17

More than 5 years have passed since last update.

ターミナルで Gif アニメーションを表示する

Last updated at Posted at 2014-04-29

こちらの記事を参考にさせて頂きました。ありがとうございます。カレンちゃん可愛い!

ターミナルに画像を表示する

そのソースコードを元に、Gif アニメーションも表示できるように拡張してみました。

#!/usr/bin/env ruby

require 'curses'
require 'rmagick'

DOT_CHAR = "  "
IMAGE_PATH = ARGV[0]
INTERVAL = ARGV[1] ? ARGV[1].to_f : nil

def pixel2color_text(pixel)
  color = [pixel.red, pixel.green, pixel.blue].map { |n| (n * 5) / (255 * 255) }
  "\x1b[48;5;#{16 + color[0] * 36 + color[1] * 6 + color[2]}m#{DOT_CHAR}\x1b[0m"
end

def screen_columns
  Curses.init_screen
  columns = Curses.cols / 2
  Curses.close_screen
  columns
end

def draw(image)
  image = image.sample((1.0 * screen_columns) / image.columns)
  rows = (0...image.rows).map do |row|
    pixels = image.get_pixels(0, row, image.columns, 1)
    pixels.map { |pixel| pixel2color_text(pixel) }.join
  end
  picture = rows.join("\n")

  puts picture
end

def animate(image_path)
  image_list = Magick::ImageList.new(image_path)
  # (ImageList#delay から算出した) デフォルトの interval 値でアニメがもっさりする場合は
  # INTERVAL の値を 0.1 などに弄ってみてください。
  interval = INTERVAL || ((1.0 * image_list.delay) / 100)

  image_list.each do |image|
    draw(image)
    sleep(interval)
  end
end

def clear_screen
  puts "\e[H\e[2J"
end

def main
  interrupted = false
  Signal.trap(:INT) { interrupted = true }

  # Ctrl + C で終了します。
  # ※ ただし、現在のアニメーションが最後のコマまで再生されるまでは終了できません。
  until interrupted do
    animate(IMAGE_PATH)
  end

  clear_screen
end

main

デモ

スクリーンショット

楽しい! ✌(’ω’✌ )三✌(’ω’)✌三( ✌’ω’)✌

17
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
17