Tips and tricks #13: Bitmaps and Pixel manipulation

This article describes how to write calculators for an image manipulation

This page exists due to the efforts of the following people:

Timur

Timur

Anton

Created: 2021-04-24 04:30:19, Last updated: 2022-04-20 10:34:18
Creative Commons Attribution/Share-Alike License 3.0 (Unported)

This content is licensed under Creative Commons Attribution/Share-Alike License 3.0 (Unported). That means you may freely redistribute or modify this content under the same license conditions and must attribute the original author by placing a hyperlink from your site to this work https://planetcalc.com/9260/. Also, please do not modify any references to the original work (if any) contained in this content.

Tips and tricks series

This article may rely on knowledge you should get from previous articles, so you may want to check them first.

To manipulate an image, you need to use the "Bitmap" input control. The loaded image is then represented by an input variable with the following properties:

  • data, the array of type Uint8ClampedArray, which holds RGBA values of the image in the range 0-255.
  • width, integer, the width of the image
  • height, integer, the height of the image

While these properties are the same as in the ImageData, the input variable is not an ImageData object. Be careful with data property manipulation - to avoid unnecessary copying, this property corresponds to image data, thus all changes will persist between calculations. So, if you want to display the original image along with the inverted image, as it is done below, copy the data array, then change the copy.

The calculator for inverting image colors below illustrates the feature. The source input variable is the variable of the "Bitmap" type, the outsource and outinv are the output variables of the "Picture" type. The "Picture" output now supports setting an ImageData object as its value.

Here is the complete code of the calculator

var src = new ImageData(source.data, source.width, source.height);
outsource.SetValue(src);
var pix = new Uint8ClampedArray(source.data);
for (var i = 0, n = pix.length; i < n; i += 4) {
    pix[i  ] = 255 - pix[i  ]; // red
    pix[i+1] = 255 - pix[i+1]; // green
    pix[i+2] = 255 - pix[i+2]; // blue
}
var inv = new ImageData(pix, source.width, source.height);
outinv.SetValue(inv);

PLANETCALC, Invert image colors

Invert image colors

Source image
  • Drag files here
Source image
 
Inverted image
 

URL copied to clipboard
PLANETCALC, Tips and tricks #13: Bitmaps and Pixel manipulation

Comments