Module: Tessel::PNG::Encoder

Defined in:
lib/tessel.rb

Class Method Summary collapse

Class Method Details

.encode(image, color_type: :rgba, filter: :none, level: Zlib::DEFAULT_COMPRESSION, metadata: image.metadata) ⇒ Object

Raises:

  • (TypeError)


365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'lib/tessel.rb', line 365

def encode(image, color_type: :rgba, filter: :none, level: Zlib::DEFAULT_COMPRESSION, metadata: image.)
  raise TypeError, "image must be a Tessel::Image" unless image.is_a?(Image)
  raise ArgumentError, "PNG dimensions must be positive" unless image.width.positive? && image.height.positive?
  type = { grayscale: 0, gray: 0, rgb: 2, palette: 3, gray_alpha: 4, rgba: 6 }.fetch(color_type.to_sym) { raise UnsupportedError, "unsupported PNG color type" }
  raise UnsupportedError, "palette PNG output needs an explicit palette" if type == 3

  raw = "".b
  previous = nil
  data = image.instance_variable_get(:@data)
  channels = { 0 => 1, 2 => 3, 4 => 2, 6 => 4 }.fetch(type)
  (0...image.height).each do |y|
    rgba = data.byteslice(y * image.width * 4, image.width * 4).bytes.each_slice(4)
    row = case type
    when 0 then rgba.map { |r, g, b, _a| (0.299 * r + 0.587 * g + 0.114 * b).round }.pack("C*")
    when 2 then rgba.flat_map { |r, g, b, _a| [r, g, b] }.pack("C*")
    when 4 then rgba.flat_map { |r, g, b, a| [(0.299 * r + 0.587 * g + 0.114 * b).round, a] }.pack("C*")
    else rgba.to_a.flatten.pack("C*")
    end
    selected = case filter.to_sym
    when :none then 0
    when :sub then 1
    when :up then 2
    when :average then 3
    when :paeth then 4
    when :adaptive
      (0..4).min_by { |kind| Filters.filter(kind, row, previous, channels).bytes.sum { |byte| byte < 128 ? byte : 256 - byte } }
    else raise ArgumentError, "unknown PNG filter: #{filter}"
    end
    raw << selected.chr << Filters.filter(selected, row, previous, channels)
    previous = row
  end

  output = SIGNATURE.dup
  Chunk.write(output, "IHDR", [image.width, image.height, 8, type, 0, 0, 0].pack("N2C5"))
  (output, )
  Chunk.write(output, "IDAT", Zlib::Deflate.deflate(raw, level))
  Chunk.write(output, "IEND", "")
  output
end