我有这段代码可读取名为someones_epi.nii.gz
的文件
该文件是二进制文件。
,然后使用此npm软件包nifti-reader-js
,我读取了此文件的内容。
我的问题是,我得到一个arrayBuffer作为响应,我想使用此arrayBuffer数据在HTML canvas元素上呈现图像,如何使用ArrayBuffers和uint8Arrays做到这一点?有人可以向我展示一个示例,该示例演示如何读取此Array缓冲区并然后在画布元素上渲染文件包含的图像。
到目前为止我的代码
<div id="target2"></div>
import * as nifti from 'nifti-reader-js';
const fs = window['require']('fs');
export class Nifti {
constructor() {
}
readNifti() {
const brainFile = './dist/assets/test/someones_epi.nii.gz';
let data = fs.readFileSync(brainFile).buffer;
let niftiHeader = null;
let niftiImage = null;
const niftiExt = null;
if (nifti.isCompressed(data)) {
data = nifti.decompress(data);
}
niftiHeader = nifti.readHeader(data);
console.log(niftiHeader.toFormattedString());
niftiImage = nifti.readImage(niftiHeader, data);
console.log('niftiImage', niftiImage);
this.draw(niftiImage);
// this.testDraw();
}
draw(arraybuffer) {
console.log('data: ', arraybuffer);
// const pixelData = new Uint8Array(arraybuffer, frameOffset, numPixels);
const screenMax = 200;
const screenMin = 200;
let screenRatio = 255 / (screenMax - screenMin);
screenRatio = 255 / (5000 - 1000);
// set up canvas
const container = document.getElementById('target2');
const canvas: HTMLCanvasElement = document.createElement('canvas');
canvas.width = 200;
canvas.width = 200;
const ctx = canvas.getContext('2d');
const imageData = ctx.createImageData(200, 200);
const alpha = 255;
const n = imageData.data.length;
for (let index = 0; index < n; index++) {
let screenValue = (arraybuffer - screenMin) * screenRatio;
screenValue = (arraybuffer - 1000) * screenRatio;
imageData.data[index] = (arraybuffer[index] >> 16) & 0xff;
imageData.data[index + 1] = (arraybuffer[index] >> 8) & 0xff;
imageData.data[index + 2] = (arraybuffer[index]) & 0xff;
imageData.data[index + 3] = alpha;
}
ctx.putImageData(imageData, 0, 0);
container.appendChild(canvas);
}
testDraw() {
const container = document.getElementById('target2');
const canvas: HTMLCanvasElement = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const imageData = ctx.createImageData(100, 100);
// Iterate through every pixel
for (let i = 0; i < imageData.data.length; i += 4) {
// Percentage in the x direction, times 255
let x = (i % 400) / 400 * 255;
// Percentage in the y direction, times 255
let y = Math.ceil(i / 400) / 100 * 255;
// Modify pixel data
imageData.data[i + 0] = x; // R value
imageData.data[i + 1] = y; // G value
imageData.data[i + 2] = 255 - x; // B value
imageData.data[i + 3] = 255; // A value
}
// Draw image data to the canvas
ctx.putImageData(imageData, 20, 20);
container.appendChild(canvas);
}
}