2

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
preston
  • 3,721
  • 6
  • 46
  • 78
  • have you checked [example on package's site](https://www.npmjs.com/package/pngjs#example)? – skyboyer Aug 03 '19 at 10:09
  • Yes because I am wanting to access the file on the client folder and not the server I cannot use the npm 'fs' package. – preston Aug 03 '19 at 11:24
  • yep, missed that. but I did not get where do you get this file from. If it's `import maze_text from '../../mazes/images/maze_text.png';` then actually file data is probably be bundled or file is on the server. Or was it just an example and you actually allows user to pick file from their local file system? – skyboyer Aug 03 '19 at 11:33
  • Not from the user's local file system but in the client side's folder structure e.g. '../../mazes/images/maze_text.png' – preston Aug 03 '19 at 11:55
  • I was partially succeeded in loading image data as base64 string with the help of webpack url-loader. but then I cannot construct `Blob` from this string to pass into `PNG`. have no idea how to move next but maybe it may help somehow. – skyboyer Aug 03 '19 at 14:40

1 Answers1

2
//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);
jiehui
  • 21
  • 2