8.1

What is a 2D array

A 2D array is an array of arrays.

image.png

Why use 2D arrays?

1D array of people

{
"Patrick Mahomes"
"Mr. Mortensen"
"Taylor Swift"
"Margot Robbie"
}

2D array of men and women

{
{ "Patrick Mahomes", "Mr. Mortensen"} ,
{"Taylor Swift", "Margot Robbie"}
}

Declaring a 2D Array

Very similar to declaring a 1D array.

DataType[] name // 1D array
DataType[][] name // 2D array
int[][] intArray; //primitive
String[][] stringArray; //object

Initalizing a 2D Array

public class TwoDArrayExample {
    public static void main(String[] args) {
        int rows = 3;
        int cols = 4;
        
        // Declare and initialize a 2D array
        int[][] myArray = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };
        
        // Access and print elements
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(myArray[i][j] + " ");
            }
            System.out.println();
        }
    }
}
TwoDArrayExample.main(null)
1 2 3 4 
5 6 7 8 
9 10 11 12 

Popcorn HACK 1

public class TwoDArrayHack1 {
    public static void main(String[] args) {
        // Declare and initialize a 2D array with 5 rows (arrays) and 4 columns (elements per array) of int data type.
        int[][] popcorn = {
            {1, 2, 3, 4},
            {1, 2, 3, 4},
            {1, 2, 3, 4},
            {1, 2, 3, 4}
        };
    }

}

More Initializing and Accessing Array Elements of a 2D Array

class Student {
    private String name;
    private int age;

    // Constructor to initialize a Student object
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter method to retrieve the student's name
    public String getName() {
        return name;
    }

    // Getter method to retrieve the student's age
    public int getAge() {
        return age;
    }

    // Method to print student information
    public void printInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

public class TwoDArrayHack2 {
    public static void main(String[] args) {
        // Declare and initialize a 2D array with 6 rows and 6 columns of Student objects
        Student[][] studentArray = new Student[6][6];

        // Creating and initializing Student objects in the array
        studentArray[0][0] = new Student("Yuri", 16);
        studentArray[1][2] = new Student("Gorlcok", 135);

        // Accessing and using the Student objects' methods
        String studentName = studentArray[0][0].getName();
        int studentAge = studentArray[0][0].getAge();

        System.out.println("Student Name: " + studentName);
        System.out.println("Student Age: " + studentAge);

        studentArray[1][2].printInfo();
    }
}
TwoDArrayHack2.main(null)

More Initializing + Accessing + Popcorn HACK 2

class NFLTeams {
    private String teamName;
    private String city;
    private int championships;

    // Constructor to initialize NFL team data
    public NFLTeams(String teamName, String city, int championships) {
        this.teamName = teamName;
        this.city = city;
        this.championships = championships;
    }

    // Method to display team information
    public void displayTeamInfo() {
        System.out.println("Team: " + teamName);
        System.out.println("City: " + city);
        System.out.println("Championships: " + championships);
    }
}

public class NFLTeams2DArray {
    public static void main(String[] args) {
        // Declare a 2D array of NFLTeams to store data for 5 teams and 5 columns
        NFLTeams[][] nflArray = {
            {new NFLTeams("Team1", "City1", 2), new NFLTeams("Team2", "City2", 3), new NFLTeams("Team3", "City3", 1), new NFLTeams("Team4", "City4", 0), new NFLTeams("Team5", "City5", 5)},
            {new NFLTeams("Team6", "City6", 3), new NFLTeams("Team7", "City7", 4), new NFLTeams("Team8", "City8", 0), new NFLTeams("Team9", "City9", 1), new NFLTeams("Team10", "City10", 2)},
            {new NFLTeams("Team11", "City11", 1), new NFLTeams("Team12", "City12", 0), new NFLTeams("Team13", "City13", 3), new NFLTeams("Team14", "City14", 2), new NFLTeams("Team15", "City15", 4)},
            {new NFLTeams("Team16", "City16", 2), new NFLTeams("Team17", "City17", 4), new NFLTeams("Team18", "City18", 1), new NFLTeams("Team19", "City19", 5), new NFLTeams("Team20", "City20", 3)},
            {new NFLTeams("Team21", "City21", 0), new NFLTeams("Team22", "City22", 2), new NFLTeams("Team23", "City23", 5), new NFLTeams("Team24", "City24", 3), new NFLTeams("Team25", "City25", 1)}
        };

        // Print out Team 17's Team info
        nflArray[3][1].displayTeamInfo();
        
        // Print out Team 21's Team Info
        nflArray[4][0].displayTeamInfo();

        // Print out Team 3's team Info
        nflArray[0][2].displayTeamInfo();

    }
}
NFLTeams2DArray.main(null)
Team: Team17
City: City17
Championships: 4
Team: Team21
City: City21
Championships: 0
Team: Team3
City: City3
Championships: 1

Updating 2D Arrays

public class Update2DArray {
    public static void main(String[] args) {
        // Create a 3x3 2D array of integers
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Display the original 2D array
        System.out.println("Original 2D Array:");
        printArray(matrix);

        // Update specific elements in the array
        matrix[0][0] = 11;  // Update the element in the first row, first column
        matrix[1][1] = 22;  // Update the element in the second row, second column
        matrix[2][2] = 33;  // Update the element in the third row, third column

        // Display the updated 2D array
        System.out.println("\nUpdated 2D Array:");
        printArray(matrix);
    }

    // Helper method to print the 2D array
    public static void printArray(int[][] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Update2DArray.main(null)

Popcorn HACK 3

public class Update2DArrayHACK {

    // Helper method to print the 2D integer array
    public static void printIntArray(int[][] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {

        // Declare and Initialize a 2D integer array with the same dimensions (5x5)
        int[][] integerArray = {
            {1, 2, 3, 4, 5},
            {6, 7, 8, 9, 10},
            {11, 12, 13, 14, 15},
            {16, 17, 18, 19, 20},
            {21, 22, 23, 24, 25}
        };

        integerArray[0][0] = 250;
        integerArray[2][2] = 69;
        integerArray[4][4] = 96;
        integerArray[0][4] = 125;
        integerArray[1][2] = 135;

     // Update the element in the first row, first column to 250
     // Update the element in the third row, third column to 69
     // Update the element in the fifth row, fifth column to 96
    // Update the element in the first row, fifth column to 125
     // Update the element in the second row, third column to 135        

        // Display the updated 2D integer array
        printIntArray(integerArray);
    }
}
Update2DArrayHACK.main(null)
250 2 3 4 125 
6 7 135 9 10 
11 12 69 14 15 
16 17 18 19 20 
21 22 23 24 96 

Popcorn HACK 4 - Review Quiz

What is a 2D array?
A. A single row of elements.
B. A data structure with rows and columns. THIS IS MY ANSWER
C. A list of 2 elements.
D. A binary representation of data.

How do you declare a 2D array in Java?
A. int myArray = new int[3][3];
B. 2DArray myArray = new 2DArray[3][3];
C. int[][] myArray; THIS IS MY ANSWER
D. myArray = declare 2D array;

How do you access an element in a 2D array at row 2 and column 3?
A. myArray[3][2]
B. myArray[2][3]
C. myArray[1][2] THIS IS MY ANSWER
D. myArray[2][1]

What is the purpose of initializing a 2D array?
A. To specify its data type.
B. To allocate memory for the array. THIS IS MY ANSWER
C. To access its elements.
D. To declare the number of rows and columns.

In a 2D array, what does myArray[2][3] represent?
A. The element in the second row and third column.
B. The element in the third row and second column.
C. The element in the third row and four column. THIS IS MY ANSWER 
D. The element in the second column and third row.

What happens when you update an element in a 2D array in Java?
A. The entire array is cleared.
B. Only the updated element is affected. THIS IS MY ANSWER
C. The entire row is shifted.
D. The element is removed from the array.

Which of the following represents a 2D array with 4 rows and 3 columns in Java?
A. int[4][3] myArray;
B. myArray[4,3] = int;
C. int[3][2] myArray; THIS IS MY ANSWER
D. myArray[3][4] = int;

HACKS

Finish Popcorn HACKS, type DONE Here when you finish

DONE

HACK 1

  • Create a class (for object 2D arrays), and declare and initialize a 2D array
  • Show updating a 2D array with object functionality
public class Motor {
  private String name;
  private int powerLevel;

  public Motor(String name, int initialPower) {
      this.name = name;
      this.powerLevel = initialPower;
  }

  public void setPowerLevel(int powerLevel) {
      this.powerLevel = powerLevel;
  }

  public int getPowerLevel() {
      return powerLevel;
  }

  public void start() {
      System.out.println(name + " motor is running.");
  }

  public void stop() {
      System.out.println(name + " motor has stopped.");
  }
}

8.2

Traversing

  • Traversing is known to acsess each element in a array also known as itteration, in the case of 2D Arrays we will acsess elements in the 2D array, but we will need to use specfiic methods of nested for loops, and enhanced for loops.
public class Motor {
    private String name;
    private int powerLevel;

    public Motor(String name, int initialPower) {
        this.name = name;
        this.powerLevel = initialPower;
    }

    public void setPowerLevel(int powerLevel) {
        this.powerLevel = powerLevel;
    }

    public int getPowerLevel() {
        return powerLevel;
    }

    public void start() {
        System.out.println(name + " motor is running.");
    }

    public void stop() {
        System.out.println(name + " motor has stopped.");
    }

    public static void main(String[] args) {
        Motor[][] motorArray = new Motor[2][2];

        motorArray[0][0] = new Motor("Motor1", 100);
        motorArray[0][1] = new Motor("Motor2", 75);
        motorArray[1][0] = new Motor("Motor3", 90);
        motorArray[1][1] = new Motor("Motor4", 80);

        // Access and update a motor's power level
        motorArray[0][0].setPowerLevel(95);

        // Start a motor
        motorArray[1][1].start();

        // Stop a motor
        motorArray[0][1].stop();

    }
}

Motor.main(null);

Motor4 motor is running.
Motor2 motor has stopped.

Nested For Loop

  • A nested for loop is a type of loop that contains an inner loop and outer loop, allowing to create a two dimensional piece that will now allow us to traverse through 2D Arrays.
public class NestedLoops {
    public static void main(String[] args) {
        for (int outer = 1; outer < 5; outer++) {
            for (int inner = 1; inner < 3; inner++) {
                System.out.print(inner + " ");
            }
            System.out.println();
        }
    }
}
NestedLoops.main(null)
1 2 
1 2 
1 2 
1 2 

Enhanced For Loop

public class EnhancedForLoopExample {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Cherry", "Date", "Fig"};

        // Here you use a en enhanced for loop to itterate through the array of strings
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}
EnhancedForLoopExample.main(null)
Apple
Banana
Cherry
Date
Fig

Cumulative Knowledge

  • Hint: Popcorn Hacks
  • From the class discussion fill these out

  • What does traverse mean?
    • to iterate
  • What is a nested loop
    • A loop inside of a loop
  • What is an enhanced for loop
    • A loop that iterates through indexes of a data structure

Nested Loops traversing through a 2D Array

public class TwoDArrayTraversal {
    public static void main(String[] args) {
        // First Create the 2D array
        int[][] twoDArray = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        
        // Using a Nested loops to traverse the 2D array
        for (int row = 0; row < 3; row++) {
            for (int col = 0; col < 3; col++) {
                int element = twoDArray[row][col];
                System.out.print(element + " ");
            }
            System.out.println(); 
        }
    }
}
TwoDArrayTraversal.main(null)
1 2 3 
4 5 6 
7 8 9 

Popcorn Hack

  • What would you replace the question marks with if we didnt know the dimensions of this 2D Array
    • twoDArray.length
    • twoDArray[i].length
public class TwoDArrayTraversal {
    public static void main(String[] args) {
        // First Create the 2D array
        int[][] twoDArray = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        
        // Using a Nested loops to traverse the 2D array
        for (int row = 0; row < ???; row++) { //grid makes sense becuase it gives you dimension
            for (int col = 0; col < ???; col++) { // colliumn makes senseas it starts at 0 
                int element = twoDArray[row][col];
                System.out.print(element + " ");
            }
            System.out.println(); 
        }
    }
}
TwoDArrayTraversal.main(null)

Practice

  • Create a 2D Array Based and Traverse through it using a nested loop based on this problem
public class TwoDPractice {
    public static void main(String[] args) {
        
        int[][] complexIntArray = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };

        for (int row = 0; row < complexIntArray.length; row++) {
            for (int col = 0; col < complexIntArray[row].length; col++) {
                int element = complexIntArray[row][col];
                System.out.print(element + " ");
            }
            System.out.println(); 
        }
    }
}

TwoDPractice.main(null);

1 2 3 4 
5 6 7 8 
9 10 11 12 

Using Enhanced For- Loops to Traverse an Array

public class EnhancedForLoop2DArray {
    public static void main(String[] args) {
        // Define and initialize a 2D array
        int[][] twoDArray = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Use nested enhanced for loops to traverse the 2D array
        for (int[] row : twoDArray) {
            for (int element : row) {
                System.out.print(element + " ");
            }
            System.out.println(); // Move to the next row
        }
    }
}
EnhancedForLoop2DArray.main(null)
1 2 3 
4 5 6 
7 8 9 

Row Major Order Vs Column Major Order

  • PopCorn Hacks

  • Whats the difference between row major order and column major order

    • row major order iterates through the rows first, column major order iterates through teh columns first
public class PrintArray {
    public static void printArray(String[][] grid) {
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[0].length; col++) {
                System.out.print(grid[row][col] + " ");
            }
            System.out.println(); 
        }
    }

    public static void main(String[] args) {
        String[][] myGrid = {
            {"A", "B", "C"},
            {"D", "E", "F"},
            {"G", "H", "I"}
        };
        printArray(myGrid);
    }
}
PrintArray.main(null)
A B C 
D E F 
G H I 
public class PrintArray {
    public static void printArray(String[][] grid) {
        for (int col = 0; col < grid[0].length; col++) // outer loop for collums switched
        { for (int row = 0; row < grid.length; row++) //notice the outer is switched with the inner loop for rows
             {
                System.out.print(grid[row][col] + " ");
            }
            System.out.println(); 
        }
    }

    public static void main(String[] args) {
        String[][] myGrid = {
            {"A", "B", "C"},
            {"D", "E", "F"},
            {"G", "H", "I"}
        };
        printArray(myGrid);
    }
}
PrintArray.main(null)
A D G 
B E H 
C F I 

Practice

  • Print My AP CS A Class Rocks Using a column major traversal.
public class PrintArray {
    public static void printArray(String[][] grid) {
        for (int col = 0; col < grid.length; col++) // outer loop for collums switched
        { for (int row = 0; row < grid[row].length; row++) //notice the outer is switched with the inner loop for rows
             {
                System.out.print(grid[col][row] + " ");
            }
            System.out.println(); 
        }
    }

    public static void main(String[] args) {
        String[][] message = {
            {"My", "Ap", "Cs", "R"},
            {"AP", "A", "Class", "o"},
            {"C", "p", " ", "c"},
            {"S", " ", " ", "k"},
            {"s", " ", "s", "!"},
        };

        printArray(message);
    }
}


PrintArray.main(null)
My Ap Cs R 
AP A Class o 
C p   c 
S     k 
s   s ! 

Algorithms That use 2D Arrays Traversing

public class SearchExample {
    public static boolean search(String[][] chart, String name) {
        for (int r = 0; r < chart.length; r++) {
            for (int c = 0; c < chart[0].length; c++) {
                if (chart[r][c].equals(name)) {
                    return true;
                }
            }
        }
        return false; // Name not found in the array
    }

    public static void main(String[] args) {
        String[][] chart = {
            {"Alice", "Bob", "Charlie"},
            {"David", "Eve", "Frank"},
            {"Grace", "Hannah", "Isaac"}
        };

        String nameToSearch = "Krishiv";
        boolean found = search(chart, nameToSearch);

        if (found) {
            System.out.println(nameToSearch + " is in the array.");
        } else {
            System.out.println(nameToSearch + " is not in the array.");
        }
    }
}
SearchExample.main(null)
Krishiv is not in the array.

Hacks 8.2

  • Complete the popcorn hacks
  • Main Hack:
    • Traverse Through a 2D Array Using Any of the following methods that we learned
    • Traverse Through A 2D Array Using Specfically The Collumn Major Order. (Make Sure your using correct type of nested loop )
    • Create your own situration of an Algorthm that needs to traverse a 2D array and then write the code for it
    • Extra: Create an Extra Problem or Go further in depth about something we learned (MUST HAVE CODE FOR CREDIT!)

Extra AP Style Problem

Problem: Consider a seating arrangement in a movie theater. The seats are organized in rows and columns. You are tasked with creating a program that helps determine the best available seat for a group of people.

Your task is to write a function that takes the following inputs:

  1. A 2D boolean array representing the theater’s seating arrangement, where true indicates a seat is already occupied, and false indicates a vacant seat.
  2. The number of people in the group (an integer).

The function should find and return the best available consecutive seats for the group. The best seats are defined as those that minimize the number of vacant seats between them.

You need to implement two versions of the function: one using row-major order and one using column-major order to traverse the 2D array. The two functions should return the same result.

public class TheaterSeating {
  public static int[] findBestSeatsRowMajor(boolean[][] theater, int groupSize) {
      int rows = theater.length;
      int cols = theater[0].length;
      int bestRow = -1;
      int bestStartCol = -1;
      int minVacantSeats = Integer.MAX_VALUE;

      for (int row = 0; row < rows; row++) {
          int vacantSeats = 0;
          int startCol = -1;

          for (int col = 0; col < cols; col++) {
              if (!theater[row][col]) {
                  vacantSeats++;
                  if (startCol == -1) {
                      startCol = col;
                  }
              } else {
                  vacantSeats = 0;
                  startCol = -1;
              }

              if (vacantSeats == groupSize && vacantSeats < minVacantSeats) {
                  bestRow = row;
                  bestStartCol = startCol;
                  minVacantSeats = vacantSeats;
              }
          }
      }

      if (bestRow == -1) {
          return null; // No suitable seats found
      }

      int[] result = new int[groupSize];
      for (int i = 0; i < groupSize; i++) {
          result[i] = bestStartCol + i;
      }
      return result;
  }

  public static int[] findBestSeatsColumnMajor(boolean[][] theater, int groupSize) {
      int rows = theater.length;
      int cols = theater[0].length;
      int bestCol = -1;
      int bestStartRow = -1;
      int minVacantSeats = Integer.MAX_VALUE;

      for (int col = 0; col < cols; col++) {
          int vacantSeats = 0;
          int startRow = -1;

          for (int row = 0; row < rows; row++) {
              if (!theater[row][col]) {
                  vacantSeats++;
                  if (startRow == -1) {
                      startRow = row;
                  }
              } else {
                  vacantSeats = 0;
                  startRow = -1;
              }

              if (vacantSeats == groupSize && vacantSeats < minVacantSeats) {
                  bestCol = col;
                  bestStartRow = startRow;
                  minVacantSeats = vacantSeats;
              }
          }
      }

      if (bestCol == -1) {
          return null;
      }

      int[] result = new int[groupSize];
      for (int i = 0; i < groupSize; i++) {
          result[i] = bestStartRow + i;
      }
      return result;
  }

  public static void main(String[] args) {
      boolean[][] theater = {
          {true, false, false, false, true},
          {true, false, false, false, false},
          {false, false, true, true, false},
          {false, false, true, true, false},
          {false, false, false, false, false}
      };

      int groupSize = 3;

      int[] bestSeatsRowMajor = findBestSeatsRowMajor(theater, groupSize);
      int[] bestSeatsColumnMajor = findBestSeatsColumnMajor(theater, groupSize);

      if (bestSeatsRowMajor != null) {
          System.out.println("Best Seats (Row Major): ");
          for (int seat : bestSeatsRowMajor) {
              System.out.print("Row " + seat + " ");
          }
      } else {
          System.out.println("No suitable seats found (Row Major).");
      }

      System.out.println();

      if (bestSeatsColumnMajor != null) {
          System.out.println("Best Seats (Column Major): ");
          for (int seat : bestSeatsColumnMajor) {
              System.out.print("Column " + seat + " ");
          }
      } else {
          System.out.println("No suitable seats found (Column Major).");
      }
  }
}

TheaterSeating.main(null);

Best Seats (Row Major): 
Row 1 Row 2 Row 3 
Best Seats (Column Major): 
Column 2 Column 3 Column 4 

Image Representation with 2D Arrays

Digital images are essentially a collection of small, discrete elements called pixels. Pixels are organized in a 2D grid, where each pixel represents a single point of color or intensity. Each element (pixel) in the 2D array corresponds to one pixel in the image. In a color image, each pixel contains three color components: Red, Green, and Blue (RGB), while in grayscale images, each pixel has a single intensity value.

Traversing and Processing an Image

Traversing an image’s 2D array involves systematically visiting every pixel in the image grid. This process often uses nested loops, with the outer loop iterating over the rows and the inner loop iterating over the columns. By traversing the array, you gain access to each pixel’s information, such as color values or intensity. This structured access is fundamental for various image processing tasks.

import java.io.*;
import java.net.URL;
import javax.imageio.ImageIO; // ImageIO is a class in Java libraries which gives an easy way to use different image formats
import java.awt.image.BufferedImage; // BufferedImage is a class in Java libraries to help perform operations on images (read + write)

public class ImageProcessing {
    public static void main(String[] args) {
        String imageUrl = "https://user-images.githubusercontent.com/111609656/277895130-d15b0768-01d9-4522-8ef7-4f8bcf69c42e.png";
        String outputFolder = "../images";
        String customFileName = "MORT1.png"; 

        try {
            String outputPath = outputFolder + File.separator + customFileName;

            URL url = new URL(imageUrl); // create URL object

            try (InputStream in = url.openStream();   // try-catch block where errors are handled
                 OutputStream out = new FileOutputStream(outputPath)) {   // input stream reads data and output stream writes the data

                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }   // reading the data from the URL and writes in 1024 byte chunks
            }

            System.out.println("Image downloaded and saved to: " + outputPath);

            File imageFile = new File(outputPath);
            BufferedImage image = ImageIO.read(imageFile); 
            int width = image.getWidth();
            int height = image.getHeight();   // get the image dimensions

            System.out.println("Success! Image Dimensions (Width x Height): " + width + " x " + height);

            // Process the image using a 2D array
            int[][] pixels = new int[width][height];

            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int pixel = image.getRGB(x, y);
                    // Process the pixel here, e.g., apply filters or transformations
                    pixels[x][y] = pixel;
                }
            }

            // Calculate resolution in pixels per inch (PPI)
            int ppi = (int) (image.getWidth() / (width * 0.0254));
            System.out.println("Resolution: " + ppi + " pixels per inch (PPI)");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
ImageProcessing.main(null)
Image downloaded and saved to: ../images/MORT1.png
Success! Image Dimensions (Width x Height): 1030 x 1372
Resolution: 39 pixels per inch (PPI)

Grayscale Conversion with Images

Grayscale conversion is a fundamental image processing operation. When converting an image to grayscale, you effectively remove color information and retain only the pixel intensity. This is typically done by calculating the average intensity from the RGB components of each pixel. The result is a grayscale image where variations in pixel intensity represent the image’s features and details. This operation can serve as a starting point for more complex image processing techniques.

import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.*;
import java.net.URL;
import javax.imageio.ImageIO;

public class ImageToGrayscaleWithArray {
    public static void main(String[] args) {
        String imageUrl = "https://user-images.githubusercontent.com/111609656/277895164-5f93f1d8-88b5-4b08-b9a1-b54fb6d55d96.png"; // Replace with the actual image URL
        String outputFolder = "../images";
        String customFileName = "MORT2_Grayscale.png"; // Change this to your desired file name for the grayscale image

        try {
            // Define the output file path
            String outputPath = outputFolder + File.separator + customFileName;

            // Create a URL object from the image URL
            URL url = new URL(imageUrl);

            // Open a connection to the URL and get the input stream
            try (InputStream in = url.openStream();
                 OutputStream out = new FileOutputStream(outputPath)) {

                // Read data from the URL and save it to the output file
                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            }

            // Read the downloaded image
            BufferedImage originalImage = ImageIO.read(new File(outputPath));
            int width = originalImage.getWidth();
            int height = originalImage.getHeight();

            // Create a 2D array to store grayscale values
            int[][] grayscaleArray = new int[width][height];

            // Convert the image to grayscale and populate the array
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int pixel = originalImage.getRGB(x, y);
                    int red = (pixel >> 16) & 0xFF;
                    int green = (pixel >> 8) & 0xFF;
                    int blue = pixel & 0xFF;
                    int gray = (red + green + blue) / 3;
                    grayscaleArray[x][y] = gray;
                }
            }

            // Save the grayscale image
            String grayscaleOutputPath = outputFolder + File.separator + customFileName;
            BufferedImage grayscaleImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int grayValue = grayscaleArray[x][y];
                    int grayPixel = (grayValue << 16) | (grayValue << 8) | grayValue;
                    grayscaleImage.setRGB(x, y, grayPixel);
                }
            }

            ImageIO.write(grayscaleImage, "png", new File(grayscaleOutputPath));

            System.out.println("Success! Image converted to grayscale, downloaded, and saved to: " + grayscaleOutputPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
ImageToGrayscaleWithArray.main(null)
Success! Image converted to grayscale, downloaded, and saved to: ../images/MORT2_Grayscale.png

Image Conversion


Why do we Convert Images ?

  • different data types have different desired qualities

How Does Image Conversion Work:

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;

public class ImageConverter {

    public static void main(String[] args) {
        try {
            // Input and output file paths
            String inputPath = "/Users/nikhilchakravarthula/vscode/KPNSLESSON/images/Mort2.png";
            String outputPath = "/Users/nikhilchakravarthula/vscode/KPNSLESSON/imagesConvert";

            // Read the PNG image
            BufferedImage img = ImageIO.read(new File(inputPath));

            // Convert image to RGB format 
            BufferedImage rgbImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
            rgbImage.createGraphics().drawImage(img, 0, 0, null);

            // Define the output file name and path
            String outputFileName = inputPath.substring(inputPath.lastIndexOf("/") + 1).replace(".png", ".jpeg");
            String outputFilePath = outputPath + File.separator + outputFileName;

            // Convert and save the image as JPEG
            ImageIO.write(rgbImage, "jpeg", new File(outputFilePath));

            System.out.println("Image conversion successful!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ImageConverter.main(null);

Scaling the Image

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageScaler {

    public static void main(String[] args) {
        try {
            // Input and output file paths
            String inputPath = "/Users/nikhilchakravarthula/vscode/KPNSLESSON/images/snow_mort.png";
            String outputPath = "/Users/nikhilchakravarthula/vscode/KPNSLESSON/imagesConvert";

            // Desired width and height of the scaled image
            int scaledWidth = 100;
            int scaledHeight = 100;

            // Read the image
            File inputFile = new File(inputPath);
            BufferedImage inputImage = ImageIO.read(inputFile);

            // Scale the image
            BufferedImage scaledImage = scaleImage(inputImage, scaledWidth, scaledHeight);

            // Write the scaled image
            String outputFileName = "scaled_" + new File(inputPath).getName();
            String outputFilePath = outputPath + File.separator + outputFileName;
            File outputFile = new File(outputFilePath);
            ImageIO.write(scaledImage, "png", outputFile);  

            System.out.println("Image scaling successful!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static BufferedImage scaleImage(BufferedImage originalImage, int scaledWidth, int scaledHeight) {
        // Create a new BufferedImage with the desired width and height
        BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, originalImage.getType());
    
        // g2d more into
        // Create a Graphics2D object and set the rendering hints for scaling
        Graphics2D g2d = scaledImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    
        // Draw the original image on the new BufferedImage with the desired width and height
        g2d.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
    
        // Dispose of the Graphics2D object
        g2d.dispose();
    
        return scaledImage;
    }
}

ImageScaler.main(null);

Image scaling successful!

Images Hack

Hack: Create a functioning code in which you convert a PNG image to a JPEG image (make it funny).

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class PNGtoJPEGConverter {
    public static void main(String[] args) {
        String inputImagePath = "../images/logo.png";
        String outputImagePath = "../images/output.jpg";

        try {
            // Read the PNG image
            BufferedImage originalImage = ImageIO.read(new File(inputImagePath));

            // Create a new BufferedImage with RGB format (JPEG)
            BufferedImage jpegImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_RGB);

            // Draw the PNG image onto the new BufferedImage
            jpegImage.createGraphics().drawImage(originalImage, 0, 0, null);

            // Write the JPEG image to the output file
            ImageIO.write(jpegImage, "jpg", new File(outputImagePath));

            System.out.println("Conversion completed successfully.");
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

PNGtoJPEGConverter.main(null);

Conversion completed successfully.

Grading for Hacks

  • 0.7 for Completing Lesson Hacks
  • 0.2 for Popcorn Hacks + Practice
  • 0.1 for Doing Extra Work