Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating image from Array in javascript and Html5

Here is my code. I created imageData 2D array in javascript. After I put all pixels into the this array, I want to create image and put these values into the image.

    var imageData = new Array(width);

    var image = new Image;

for (var i = 0; i < width; i++) {
    imageData[i] = new Array(height);
}

    image.src = imageData; //Here is the problem. I want to do that. 
like image 685
user3470518 Avatar asked Apr 02 '14 21:04

user3470518


1 Answers

You can't make an image.src like that.

A valid dataURL is a base64 encoded string with a type prefix--not an array.

The image data array associated with a canvas is an Uint8ClampedArray--not a normal javascript array.

Here's one way to create a pixel array that you can manipulate:

A Demo: http://jsfiddle.net/m1erickson/956kC/

// create an offscreen canvas
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");

// size the canvas to your desired image
canvas.width=40;
canvas.height=30;

// get the imageData and pixel array from the canvas
var imgData=ctx.getImageData(0,0,40,30);
var data=imgData.data;

// manipulate some pixel elements
for(var i=0;i<data.length;i+=4){
    data[i]=255;   // set every red pixel element to 255
    data[i+3]=255; // make this pixel opaque
}

// put the modified pixels back on the canvas
ctx.putImageData(imgData,0,0);

// create a new img object
var image=new Image();

// set the img.src to the canvas data url
image.src=canvas.toDataURL();

// append the new img object to the page
document.body.appendChild(image);
like image 130
markE Avatar answered Sep 18 '22 13:09

markE