module ChunkyPNG::Canvas::PNGEncoding

def encode_png_image_pass_to_stream(stream, color_mode)

Parameters:
  • color_mode (Integer) -- The color mode to use for encoding.
  • String, (String, IO, :<<] stream The stream to write to.) -- IO, :<<] stream The stream to write to.
def encode_png_image_pass_to_stream(stream, color_mode)
  case color_mode
  when ChunkyPNG::COLOR_TRUECOLOR_ALPHA
    stream << pixels.pack("xN#{width}" * height)
    
  when ChunkyPNG::COLOR_TRUECOLOR 
    line_packer = 'x' + ('NX' * width)
    stream << pixels.pack(line_packer * height)
    
  else
    pixel_size = Color.bytesize(color_mode)
    pixel_encoder = case color_mode
      when ChunkyPNG::COLOR_TRUECOLOR       then lambda { |color| Color.to_truecolor_bytes(color) }
      when ChunkyPNG::COLOR_TRUECOLOR_ALPHA then lambda { |color| Color.to_truecolor_alpha_bytes(color) }
      when ChunkyPNG::COLOR_INDEXED         then lambda { |color| [encoding_palette.index(color)] }
      when ChunkyPNG::COLOR_GRAYSCALE       then lambda { |color| Color.to_grayscale_bytes(color) }
      when ChunkyPNG::COLOR_GRAYSCALE_ALPHA then lambda { |color| Color.to_grayscale_alpha_bytes(color) }
      else raise "Cannot encode pixels for this mode: #{color_mode}!"
    end
    previous_bytes = Array.new(pixel_size * width, 0)
    each_scanline do |line|
      unencoded_bytes = line.map(&pixel_encoder).flatten
      stream << encode_png_scanline_up(unencoded_bytes, previous_bytes, pixel_size).pack('C*')
      previous_bytes = unencoded_bytes
    end
  end
end