...
/Implement the Image Rotation Feature
Implement the Image Rotation Feature
Learn how to implement the image rotation functionality by manipulating 3D arrays.
Introduction
In the previous lesson, we implemented the functions to upload and save (download) an image rendered on the canvas. In this lesson, we'll be implementing the functions to rotate an image to the right (clockwise direction) or the left (counterclockwise direction).
As already discussed, an image contains integer values denoting each pixel, and each pixel contains four values: red, green, blue, and alpha (RGBA). The problem here is that we can only render images represented in the 1D array on the canvas. So, we need to implement two utility functions—first, to convert the 3D array into a 1D array (in other words, flatten the array) and then to revert the 1D array to its corresponding 3D array representation. A 3D array is actually a 2D array of which every element contains another array. So, in the case of images, every pixel is an element in the 2D array (matrix) as well as in another array of size 4, denoting the RGBA values. So, to flatten the 3D array, for every pixel at position (i, j)
in the 3D array, we can flatten it by using the following formula:
OneDArray[(i * cols + j) * 4 + k] = ThreeDArray[i][j]
In the above formula,
cols
is the number of columns in the 3D array.i
andj
are the position of the pixel in the 3D array.k
is the count of the four values of each pixel (RGBA) in the range 0 to 3.
Below is a simple illustration in which we have a 3D array (a 2D array/matrix in which each element is an array of size 4) that is flattened to a 1D array.
Now let's go ahead and write our first utility function to convert the 3D array to its corresponding 1D array.
Convert the 3D array to a 1D array
We'll be following the steps below: ...