How to convert 16bit raw data into png image to show in browser?

1k views Asked by At

I have 16 bit raw data as base64 string. Want to convert that into png image, based on depth 8,16,24.

// code to process 16bit buffer array
function process16bitBitmap(buffer, options = {}) {
const view = new Uint8ClampedArray(buffer);
const out = new Uint8ClampedArray(buffer.byteLength);
// set alpha channel
view.forEach((a, i) => out[(i * 4) + 3] = a);
const canvas = document.createElement('canvas');
canvas.width = options.width;
canvas.height = options.height;
const imgData = new ImageData(out, options.width, options.height);
canvas.getContext('2d').putImageData(imgData, 0, 0);
// if you want to save a png version
document.body.appendChild(canvas);}

fiddle to reproduce the issue jsfiddle

Facing hard time to correctly create a png file from 16 bit raw data. 16 bit image should looks like this.

enter image description here

1

There are 1 answers

0
Luigi Minardi On

With javaScript Vanilla:

I found this but coundn't find a way to reproduce.

With nodejs:

I found this and it works fine. Also found this but didn't work for me.

const fs = require('fs');
const path = require('path');

const base64ToPNG = (data) => {
    data = data.replace(/^data:image\/png;base64,/, '');

    fs.writeFile(path.resolve(__dirname, 'image.png'), data, 'base64', function (err) {
        if (err) throw err;
    });
}

var img = "YourImageHere...iVBORw0KGgoAAAANSUhEUgAAANwAAADcCAYAAAAbWs+...";

base64ToPNG(img)

If your objective is doing it with vanilla I don't know if I could help you, with node that way works, so probably you'll just need to figure how to adjust the depth.