Module: Tessel::PNG::Filters

Defined in:
lib/tessel.rb

Class Method Summary collapse

Class Method Details

.filter(type, row, previous, bpp) ⇒ Object



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/tessel.rb', line 333

def filter(type, row, previous, bpp)
  bytes = row.bytes
  prior = previous ? previous.bytes : Array.new(bytes.length, 0)
  bytes.each_index.map do |i|
    left = i >= bpp ? bytes[i - bpp] : 0
    up = prior[i]
    upper_left = i >= bpp ? prior[i - bpp] : 0
    value = case type
    when 0 then bytes[i]
    when 1 then bytes[i] - left
    when 2 then bytes[i] - up
    when 3 then bytes[i] - ((left + up) / 2)
    when 4 then bytes[i] - paeth(left, up, upper_left)
    else raise ArgumentError, "unknown PNG filter: #{type}"
    end
    value & 255
  end.pack("C*").b
end

.unfilter(type, row, previous, bpp) ⇒ Object



319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/tessel.rb', line 319

def unfilter(type, row, previous, bpp)
  bytes = row.bytes
  prior = previous ? previous.bytes : Array.new(bytes.length, 0)
  case type
  when 0 then bytes
  when 1 then bytes.each_index { |i| bytes[i] = (bytes[i] + (i >= bpp ? bytes[i - bpp] : 0)) & 255 }
  when 2 then bytes.each_index { |i| bytes[i] = (bytes[i] + prior[i]) & 255 }
  when 3 then bytes.each_index { |i| bytes[i] = (bytes[i] + (((i >= bpp ? bytes[i - bpp] : 0) + prior[i]) / 2)) & 255 }
  when 4 then bytes.each_index { |i| bytes[i] = (bytes[i] + paeth(i >= bpp ? bytes[i - bpp] : 0, prior[i], i >= bpp ? prior[i - bpp] : 0)) & 255 }
  else raise DecodeError, "unknown PNG filter: #{type}"
  end
  bytes.pack("C*").b
end