Implement the Image Flip Feature

Learn how to implement the image flip functionality by manipulating 3D arrays.

Introduction

In the previous lessons, we implemented the functions to upload, save, and rotate an image to the left and right. In this lesson, we'll be implementing the functions to flip an image along the horizontal and the vertical axes. As we did before, we are going to add these functions in the same tools object. Let's move on to the implementation.

Function to flip an image along the horizontal axis

Below is an illustration of the logic to flip the pixel values of an image horizontally. Suppose we have an image with 3×33\times 3 pixels. Now, after flipping the image along the horizontal axis, the first rows get swapped with the last rows. This means we've flipped the pixel values of the image, which is the same as saying that we've flipped the image along the horizontal axis.

Press + to interact
Image flipped along the horizontal axis
Image flipped along the horizontal axis

Here's the code:

Press + to interact
const tools = {
// Upload, save, rotateLeft, and rotateRight functions created in an earlier lesson
"flipHorizontal" : function(){
// Store the width and height of the canvas which is equivalent to the
// width and height of the image
let cols = editor.width;
let rows = editor.height;
// Get the RGBA array of the image displayed on the canvas
let image = getRGBArray(rows, cols);
// Iterate the rows till the mid row of the 3D array
for(let i = 0; i < Math.floor(rows/2); i++){
// Iterate over all the columns in the row
for(let j = 0; j < cols; j++){
// Swap the pixel value at (i, j) with (rows - 1 - i, j)
let tmp = image[i][j];
image[i][j] = image[rows-1-i][j];
image[rows-1-i][j] = tmp;
}
}
// Convert the RGBA array to 1D array and render the image on the canvas
setImageData(image, rows, cols);
}
};

Explanation

We've already added the upload()save(), rotateLeft(), and rotateRight() functions in the tools object. In the code above, we've removed the earlier functions, just to make things more compact and clear.

    ...