Reputation: 462
I want to generate random images using some random function into an Uint8Array in reactjs. Now I want to render it through tag. For example:
img = new Uint8Array(100 * 100 * 3); // want to create a 100 * 100 3 channel color image
//someRandomFunction(img);
let blob = new Blob( [ img ], { type: "image/png" } );
var urlCreator = window.URL || window.webkitURL;
const imageUrl = urlCreator.createObjectURL( blob );
Now I want to render this "imgUrl" in the img tag.
I have converted this data into a blob and created a URL to set the image source. However, no luck so far. It always shows some 0x0 empty image. Even when I have an all zero array, shouldn't it show a complete black image ?
Just to give a little bit more context, essentially, I am trying to copy the behavior of numpy and opencv from python. There we can create a numpy array and then show that image through opencv function like this:
img = np.random.randint([100, 100, 3], dtype=np.uint8)
cv2.imshow('image', img);
How can I achieve that in reactjs ? Can anyone please help me out here ?
Upvotes: 1
Views: 1124
Reputation: 450
You can try with Uint8ClampedArray
, ImageData
and canvas
instead of img
.
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const arr = new Uint8ClampedArray(40000);
// Iterate through every pixel
for (let i = 0; i < arr.length; i += 4) {
arr[i + 0] = 0; // R value
arr[i + 1] = 190; // G value
arr[i + 2] = 0; // B value
arr[i + 3] = 255; // A value
}
// Initialize a new ImageData object
let imageData = new ImageData(arr, 200);
// Draw image data to the canvas
ctx.putImageData(imageData, 20, 20);
For more information you can see MDN ImageData and Uint8ClampedArray
Upvotes: 1