Image Processing 2. Simple transformation
2 min read June 09, 2025 #image processing #javascriptIn this article, we'll implement flipping and 90°/270° rotations for images. But before doing that, let's explore image pixel data and how to access it in JavaScript.
Images#
This is quite straightforward: an image is a collection of colored dots called pixels. An image has width, height, and other parameters, which we'll discuss later.
You can think of an image as a 2D array. To get the bottom-right pixel, simply subtract 1 from both width and height (remember arrays are indexed from zero and we typically access rows first and then the columns):
pixel = img[height - 1][width - 1]
.
Although this representation seems convenient, in practice, an image is often represented as a 1D array of length width*height
:
Look what they did to Kenny
Here, the bottom-right pixel is obtained as follows: pixel = img[img.length - 1]
. To get a pixel at coordinate (x, y), you need to move by y
rows and x
positions: (y * width + x)
.
Getting Pixels from <img>
#
To get a pixel array from an <img>
tag, you need to:
- Obtain the
img
tag object - Get or create a canvas
- Set the canvas size to match the image dimensions
- Render the image
// <img id="image1" src="..." />
// img = getImageData('image1');
However, due to security restrictions, you can only render images in the canvas that support CORS, or encode the image in base64. I'll use the latter approach in my examples.
Flipping and 90°/270° Rotation#
We don't need to split pixels into color components yet, because flipping and rotating involve manipulating pixel positions. Recall computer science lessons about matrix operations and transposition, that's exactly what should be done.
Horizontal Flip: For each position x
, draw the pixel from position (width - x - 1)
:
for ; y < height; y++
Vertical Flip: For each position y
, draw the pixel from position (height - y - 1)
:
for ; y < height; y++
90° Rotation: Here, width becomes height and height becomes width, so we need to create a new canvas with adjusted dimensions:
;
;
for ; y < newHeight; y++
270° Rotation:
;
;
for ; y < newHeight; y++
I'll leave implementing simultaneous horizontal + vertical flips as a homework exercise. The solution will be in the next article.