save image in different bitdepth matlab in javascript

To save an image in different bit-depths in MATLAB, you can use the imwrite function with the desired bit-depth specified in the options. Here's an example code snippet:

main.m
% Load an image in MATLAB.
img = imread('example.jpg');

% Convert the image to grayscale.
grayImg = rgb2gray(img);

% Save the image in 8-bit grayscale.
imwrite(grayImg, 'example_8bit_grayscale.jpg', 'BitDepth', 8);

% Save the image in 16-bit grayscale.
imwrite(grayImg, 'example_16bit_grayscale.png', 'BitDepth', 16);
321 chars
12 lines

In JavaScript, you can use the HTML5 Canvas element to manipulate images and save them with different bit-depths. Here's an example code snippet:

index.tsx
// Load an image in JavaScript.
var img = new Image();
img.src = 'example.jpg';

// Wait for the image to load.
img.addEventListener('load', function() {
  // Create a canvas element.
  var canvas = document.createElement('canvas');
  canvas.width = img.width;
  canvas.height = img.height;

  // Draw the image on the canvas element.
  var ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0);

  // Get the image data from the canvas.
  var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

  // Create a new canvas element for the output image.
  var outputCanvas = document.createElement('canvas');
  outputCanvas.width = canvas.width;
  outputCanvas.height = canvas.height;

  // Draw the image data on the output canvas with 8-bit depth.
  var outputCtx = outputCanvas.getContext('2d');
  outputCtx.putImageData(imageData, 0, 0, 0, 0, canvas.width, canvas.height);
  outputCtx.drawImage(outputCanvas, 0, 0, canvas.width, canvas.height);

  // Save the 8-bit image.
  var link = document.createElement('a');
  link.download = 'example_8bit.png';
  link.href = outputCanvas.toDataURL('image/png');
  link.click();

  // Draw the image data on the output canvas with 16-bit depth.
  var outputCtx2 = outputCanvas.getContext('2d', {alpha: false});
  var imageData16 = Uint16Array.from(imageData.data);

  for (var i=0; i<imageData.data.length; i+=4) {
    var pixelValue = imageData.data[i];
    imageData16[i/4] = pixelValue * (65535/255);
  }

  imageData.data.set(new Uint8ClampedArray(imageData16.buffer));
  outputCtx2.putImageData(imageData, 0, 0, 0, 0, canvas.width, canvas.height);
  outputCtx2.drawImage(outputCanvas, 0, 0, canvas.width, canvas.height);

  // Save the 16-bit image.
  link.download = 'example_16bit.png';
  link.href = outputCanvas.toDataURL('image/png');
  link.click();
});
1825 chars
53 lines

This code uses the download attribute of an HTML anchor link and the toDataURL function of the canvas element to save the output image. Note that the second putImageData call is used to convert the data to 16-bit depth.

gistlibby LogSnag