Search code examples
javascriptrubychunkypngpngjs

Understanding and Converting Ruby's ChunkyPNG to Javascript Equivalent


I am converting some RUBY code into Javascript. This RUBY code uses ChunkyPNG Ruby Library.

Here is the Ruby Code:

def self.from_png(file)
  image = ChunkyPNG::Image.from_file(file)
  mask = Mask.new(image.height, image.width)

  mask.rows.times do |row|
    mask.columns.times do |col|
      if image[col, row] == ChunkyPNG::Color::BLACK
        mask[row, col] = false
      else
        mask[row, col] = true
      end
    end
  end

  mask
end

How to convert the above code to Javascript? The 2 lines I am facing challenges with converting are:

image = ChunkyPNG::Image.from_file(file)

and

if image[col, row] == ChunkyPNG::Color::BLACK

What Javascript PNG library can I use to do the same?

What does

image[col, row]

refer to? is it RG in RGB?? or what is it? Understanding this can help me find the equivalent Javascript method in Javascript PNG Libraries ...


Solution

  • image[col, row] refers to specific pixel of the image at position (col, row). Image can be described as 2D array of colors - in this case, color is an instance of ChunkyPNG::Color or just a number. In your code sample all black pixels marked as false in the mask, all non-black marked as true.