React: How to Read a PNG in the client/browser and parse it to PNGJS

1.7k Views Asked by At

I am using React JS to develop my application.

I know how to import an image in the client/browser folder structure

In my case:

import maze_text from '../../mazes/images/maze_text.png';

I would like to read that PNG file so I can pass it to PNGJS

e.g.

var PNG = require('pngjs').PNG

I would like it to pass it to 'pngjs' so that PNGJS can parse the whole png file and check each pixel in the image for its color, etc.

I have tried:

var FileReader = new window.FileReader()
var imageData = FileReader.readAsArrayBuffer(maze_text)

But I get the following error:

Mazes.js:51 Uncaught TypeError: Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob'.

Basically what I am trying to achieve is to translate the Ruby code below into a Javascript equivalent using pngjs since there is no ChunkyPNG in Javascript:

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
1

There are 1 best solutions below

0
On
//assuming you have a Input with "fileInput" id
var file = document.getElementById('fileInput').files[0];
var filereader = new FileReader();
filereader.onloadend = function(event) {
    new png.PNG({filterType: 4}).parse(event.target.result, function(error, image){
        if(error){return;}
        //image is the PNG image
    });
};
filereader.readAsArrayBuffer(file);