Snippets

cia_rana Ruby+RMagickで端末上に画像をモザイクで表示する

Created by cia_rana
equire 'RMagick'
require 'curses'

include Magick
include Curses

def convert(c = [255, 0, 0, 0])
  c.map { |c| c == 0 ? 0 : (c.to_f / 42.5).ceil - 1 }
end

def color_palet(convert_color)
  16+convert_color.each_with_index.inject(0) { |s, (c, m)| s + c*6**(2-m) }
end

def fetch_pixel_color(img)
  img.rows.times.map do |y|
    img.columns.times.map do |x|
      pixel = img.pixel_color(x, y)
      [pixel.red, pixel.green, pixel.blue].map { |p| p>>8 }
    end
  end
end

def display_size
  init_screen
  height, width = lines, cols
  close_screen
  [width, height]
end

def output_image(x, y, pixel_color)
  buf = ""
  y.times do |_y|
    x.times do |_x|
      buf << "\e[38;5;#{color_palet(convert(pixel_color[_y][_x]))}m●"
    end
    buf << "\e[38;5;0m\n"
  end
  puts buf
end

def decide_scale(x, y, width, height)
  return [width.to_f/x, height.to_f/y].min if x > width || y > height
  return [x.to_f/width, y.to_f/height].min if x < width && y < height
  return 1
end

IMAGE_FILE = ARGV[0] || "./img/sample.png"
img = ImageList.new(IMAGE_FILE)
#img.alpha Magick::DeactivateAlphaChannel
#img = img.opaque_channel("#FFFFFF", "#000000")
display_width, display_height = display_size
new_img = img.scale((img.columns*((display_height+1).to_f/img.rows)+1).ceil, display_height+1)
output_image(new_img.columns, new_img.rows, fetch_pixel_color(new_img))
puts "width:#{display_width}, height:#{display_height}, col:#{new_img.columns}, rows:#{new_img.rows}"

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.