Class: Aspera::Preview::Backend::ChunkyPNG

Inherits:
Base
  • Object
show all
Defined in:
lib/aspera/preview/terminal.rb

Instance Method Summary collapse

Methods inherited from Base

#terminal_scaling

Constructor Details

#initialize(blob, **kwargs) ⇒ ChunkyPNG

Initialize the ChunkyPNG-backed decoder for a PNG payload.

Parameters:

  • blob (String)

    PNG binary content

  • kwargs (Hash)

    forwarding options accepted by [‘initialize`](lib/aspera/preview/terminal.rb:16)



75
76
77
78
79
# File 'lib/aspera/preview/terminal.rb', line 75

def initialize(blob, **kwargs)
  super(**kwargs)
  require 'chunky_png'
  @png = ::ChunkyPNG::Image.from_blob(blob)
end

Instance Method Details

#terminal_pixelsArray<Array<Array<Integer>>>

Resize the PNG using nearest-neighbor sampling and return RGB pixel rows.

Returns:

  • (Array<Array<Array<Integer>>>)

    rows of ‘[red, green, blue]` pixel triplets



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/aspera/preview/terminal.rb', line 84

def terminal_pixels
  src_w = @png.width
  src_h = @png.height
  dst_w, dst_h = terminal_scaling(src_h, src_w)
  dst_w = [dst_w, 1].max
  dst_h = [dst_h, 1].max
  pixel_colors = Array.new(dst_h){Array.new(dst_w)}
  x_ratio = src_w.to_f / dst_w
  y_ratio = src_h.to_f / dst_h
  dst_h.times do |dy|
    sy = (dy * y_ratio).floor
    sy = src_h - 1 if sy >= src_h
    dst_w.times do |dx|
      sx = (dx * x_ratio).floor
      sx = src_w - 1 if sx >= src_w
      rgba = @png.get_pixel(sx, sy)
      # ChunkyPNG stores pixels as 0xRRGGBBAA; extract 8-bit RGB channels.
      pixel_colors[dy][dx] = %i[r g b].map{ |i| ::ChunkyPNG::Color.send(i, rgba)}
    end
  end
  pixel_colors
end