Reputation: 405
I have a python array with shape 64x64x3. Thus 64 width, 64 height and 3 RGB pixel values.
How do I render this pixel array on my website?
Is there for example a way to let the <img>
tag read in a pixel array instead of a filename?
Solutions with JavaScript arrays are good as well.
Upvotes: 2
Views: 1728
Reputation: 1436
You could use a <canvas>
element and render the pixels programmatically.
The MDN has a great article on canvas where they give an example of reading and writing pixels programatically.
var canvas = document.getElementById('rasterCanvas');
var ctx = canvas.getContext('2d');
// get current raster data
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data;
// prepare data
for(var i = 0; i < data.length; i++) {
data[i] = Math.random() * 255;
}
// draw newly modified pixels back onto the canvas
ctx.putImageData(imageData, 0, 0);
<canvas id="rasterCanvas" style="width: 100px; height: 100px; border: 1px solid red"></canvas>
Upvotes: 2
Reputation: 619
For a full Javascript based answer see below. I went with HTML5 Canvas as it's easy to use and you can just set individual pixels on your canvas.
Note: The array is only 5x5x3 because I did it by hand, but the concept should be fairly obvious.
var ctx = document.getElementById('imageCanvas').getContext('2d');
var imageData = [
[[255,0,0], [255,0,0], [255,0,0], [255,0,0], [255,0,0]],
[[0,255,0], [0,255,0], [0,255,0], [0,255,0], [0,255,0]],
[[255,0,0], [255,0,0], [255,0,0], [255,0,0], [255,0,0]],
[[0,255,0], [0,255,0], [0,255,0], [0,255,0], [0,255,0]],
[[255,0,0], [255,0,0], [255,0,0], [255,0,0], [255,0,0]],
];
for(var y = 0; y < imageData.length; y++){
for(var x = 0; x < imageData[y].length; x++){
ctx.fillStyle = `rgb(${imageData[y][x][0]}, ${imageData[y][x][1]}, ${imageData[y][x][2]})`;
ctx.fillRect( x, y, 1, 1 );
}
}
<canvas id="imageCanvas" width="64" height="64" style="border:1px solid #000000;">
</canvas>
Upvotes: 0
Reputation: 2244
You need to save the array to an image file first, and then link it using the <img>
tag.
Here's an example using the PIL
library:
from PIL import Image
imageFile = Image.new('RGB', (len(myArray[0]), len(myArray)))
imageFile.putdata([tuple(p) for row in myArray for p in row])
imageFile.save("example.png")
Upvotes: 0