I am trying to create an image (in black and white) by using an array of pixels from a JSON file, but I get the error: ‘Image type is unsupported’. Here is the code I used:
const dimensions = [imageArray.length, imageArray[0].length];
var width = dimensions[1],
height = dimensions[0],
buffer = new Uint8ClampedArray(width * height * 4); // have enough bytes
for(var y = 0; y < height; y++) {
for(var x = 0; x < width; x++) {
var pos = (y * width + x) * 4; // position in buffer based on x and y
buffer[pos] = imageArray[y][x]; // some R value
buffer[pos+1] = imageArray[y][x]; // some G value
buffer[pos+2] = imageArray[y][x]; // some B value
buffer[pos+3] = 255; // set alpha channel
}
}
const image = figma.createImage(Uint8Array.from(buffer));
The data passed in must be encoded as a PNG, JPEG, or GIF - I assume it’s missing the right header data to be one of those data types. You need to find another library or more likely an online service to convert the raw pixel data to a PNG or GIF stream first. It would be simpler to send a GIF/PNG in the JSON. Most GIF convertors are written in C for performance - there are some javascript encoders and a lot of online services like object convert Pure JavaScript HTML5 <canvas> to (Animated) GIF Conversion
I tried to convert it back to PNG and it does work.
In my code, I then convert the retrieved string variable from the JSON and convert it to UTF-8 Bytes and then convert it to an Uint8Array to pass it to figma.createImage().