Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access image data in Elm?

How do we get the Pixel data from images in Elm?


Here in JavaScript, is code to get the color of a set of pixels in a figure (taken from here)

var image = new Image;
image.src = "starry-night.jpg";

var canvas  = d3.select("body").append("canvas");
var context = canvas.node().getContext("2d");

context.drawImage(image, 0, 0);

// beware variable name "image" got used twice
image = context.getImageData(0, 0, width, height);

var x = Math.random()*width,
    y = Math.random()*height,
    i = (y * width + x) << 2;

pixelColor = d3.rgb(image.data[i + 0], image.data[i + 1], image.data[i + 2]) + "";

The code loads an image to a <canvas> element, then extracts the color of a pixel from the canvas using image.getImageData().

Can we interface the image.data object in Elm? Right now I don't think it's possible...

  • Right now Collage types are list of forms...
  • HTML is also a module that can put imags in the DOM.
  • SVG allows for some simple global image transformations but nothing at the pixel level

Elm has the Virtual Dom. In fact of problems like this, might be addressed in virtual-dom which is lower level so we are not encouraged to do this directly.

However, Elm makes a clear distinction between Collage elements and SVG elements, with no clear interface to the getImageData() function.

  • Do I write my own with Elm's new interOp feature?
  • Does a way already exist in Elm? Or a new one has to be written?

JavaScript

  • The << operator is called Left Shift
like image 303
john mangual Avatar asked May 31 '16 14:05

john mangual


1 Answers

As suggested by @SimonH, use a port to JS until Elm provides a first-hand way to do so (if it ever does). The same approach would apply to anything you can't yet do in Elm.

I'm just answering as an answer rather than a comment for the sake of others who come here.

like image 143
Ethan B. Martin Avatar answered Oct 12 '22 16:10

Ethan B. Martin