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 rows = 5;
        int cols = 4;

        int[][] myArray = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12},
            {13, 14, 15, 16},
            {17, 18, 19, 20}
        };

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(myArray[i][j] + " ");
            }
            System.out.println();
        }
    }

}
TwoDArrayHack1.main(null)
1 2 3 4 
5 6 7 8 
9 10 11 12 
13 14 15 16 
17 18 19 20 

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}
        };

     // Update the element in the first row, first column to 250
     integerArray[0][0]=250;
     // Update the element in the third row, third column to 69
     integerArray[2][2]=69;
     // Update the element in the fifth row, fifth column to 96
     integerArray[4][4]=96;
    // Update the element in the first row, fifth column to 125
    integerArray[0][4]=125;
     // Update the element in the second row, third column to 135      
     integerArray[1][2]=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?
B. A data structure with rows and columns.

How do you declare a 2D array in Java?
C. int[][] myArray;

How do you access an element in a 2D array at row 2 and column 3?
C. myArray[1][2]

What is the purpose of initializing a 2D array?
B. To allocate memory for the array.

In a 2D array, what does myArray[2][3] represent?
C. The element in the third row and fourth column.

What happens when you update an element in a 2D array in Java?
B. Only the updated element is affected.

Which of the following represents a 2D array with 4 rows and 3 columns in Java?
A. int[4][3] myArray;

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
import java.util.Scanner;

public class KaidenArrayClass {
    public static void printKaidenArray(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) {
        int[][] KaidenArray = {
            {1,2,3},
            {4,5,6},
            {7,8,9}
        };
        printKaidenArray(KaidenArray);
        boolean changing = true;
        Scanner myObj = new Scanner(System.in);
        while(changing){
            System.out.println("Do you want to change stuff?(y or n)");
            String change = myObj.nextLine();
            if(change.equals("y")){
                System.out.println("Row to change");
                int rowChange = Integer.parseInt(myObj.nextLine()) -1;
                System.out.println("Column to change");
                int colChange = Integer.parseInt(myObj.nextLine())-1;
                System.out.println("Number to put");
                int newNum = Integer.parseInt(myObj.nextLine());
                KaidenArray[rowChange][colChange] = newNum;
                printKaidenArray(KaidenArray);
            }
            else{
                changing = false;
            }
        }


    }
}
KaidenArrayClass.main(null);
1 2 3 
4 5 6 
7 8 9 
Do you want to change stuff?(y or n)
Row to change
Column to change
Number to put
1 2 3 
4 5 6 
7 1000 9 
Do you want to change stuff?(y or n)

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 ArrayTraversalExample {
    public static void main(String[] args) {
        // Array that is created in order to be traversed/itterate through
        int[] numbers = {1, 2, 3, 4, 5};

        // Traverse the array and print each element
        // How this works: 1. First it sets i to 0 in order to keep track of the index by using a for loop
        // Then it checks if the number is greater index if so then it will continue
        // uses i++ to continue to go through the indicies 
        // prints outs the number if greater than index
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Element at index " + i + " is: " + numbers[i]);
        }
    }
}
ArrayTraversalExample.main(null)
Element at index 0 is: 1
Element at index 1 is: 2
Element at index 2 is: 3
Element at index 3 is: 4
Element at index 4 is: 5

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 visit each item in the array
  • What is a nested loop a loop in a loop
  • What is an enhanced for loop a for loop that uses (int:array) to traverse the array without using the index

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
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 < twoDArray.length; row++) { //grid makes sense becuase it gives you dimension
            for (int col = 0; col < twoDArray[0].length; col++) { // colliumn makes senseas it starts at 0 
                int element = twoDArray[row][col];
                System.out.print(element + " ");
            }
            System.out.println(); 
        }
    }
}
TwoDArrayTraversal.main(null)
1 2 3 
4 5 6 
7 8 9 

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}
        };

       // MISSING CODE HERE 
        for (int row = 0; row < complexIntArray.length; row++) {
            for (int col = 0; col < complexIntArray[0].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 is by iterating through the rows, then the columns within, but the colum major is the other way

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[0].length; col++) {
            for (int row = 0; row < grid.length; row++) {
                System.out.print(grid[row][col] + " ");
            }
            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 C S s 
Ap A p     
Cs Class     s 
R o c k ! 

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!)
// There is a hotel with 5 floors and 10 rooms for each floor. There are squares in all rooms except one with an apple. Find the floor and room of the apple
public class findApple {
    public static String searchHotel(String[][] hotel, String findem) {
        for (int r = 0; r < hotel.length; r++) {
            for (int c = 0; c < hotel[0].length; c++) {
                if (hotel[r][c].equals(findem)) {
                    return "Apple is on floor " + (r+1) + " and in room " + (c+1);
                }
            }
        }
        return "Apple is not here"; // Name not found in the array
    }

    public static void main(String[] args) {
        String[][] hotel = {
            {"square", "square", "square", "square", "square", "square", "square", "square", "square", "square"},
            {"square", "square", "square", "square", "square", "square", "square", "square", "square", "square"},
            {"square", "square", "square", "square", "square", "square", "square", "apple", "square", "square"},
            {"square", "square", "square", "square", "square", "square", "square", "square", "square", "square"},
            {"square", "square", "square", "square", "square", "square", "square", "square", "square", "square"}
        };

        String whotofind = "apple";
        String location = searchHotel(hotel, whotofind);
        System.out.println(location);
    }
}
findApple.main(null)
Apple is on floor 3 and in room 8

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 ?

Bc we might need certain files, each format has different quality and compatibilities

How Does Image Conversion Work:

import javax.imageio.ImageIO; // allows you to read and write images in various formats.
import java.io.File; // allows you to work with files and directories in your file system.
import java.io.IOException; // allows you to handle input and output exceptions that may occur during file operations.
import java.awt.image.BufferedImage; // allows you to work with images stored in memory, providing methods to manipulate image data.

public class ImageConverter {

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

            // Loop through each image in the array
            for (String inputPath : inputPaths) {
                // Read the image
                File inputFile = new File(inputPath);
                BufferedImage img = ImageIO.read(inputFile);  // Buffered image is a class in java for handling image data

                // Write the image
                String outputFileName = "converted_" + new File(inputPath).getName().replace(".png", ".gif");
                String outputFilePath = outputPath + File.separator + outputFileName;
                File outputFile = new File(outputFilePath);
                ImageIO.write(img, "gif", outputFile);

                System.out.println("Image conversion successful for: " + inputPath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
ImageConverter.main(null)

javax.imageio.IIOException: Can't read input file!
	at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
	at REPL.$JShell$42F$ImageConverter.main($JShell$42F.java:38)
	at REPL.$JShell$78.do_it$($JShell$78.java:22)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at io.github.spencerpark.ijava.execution.IJavaExecutionControl.lambda$execute$1(IJavaExecutionControl.java:95)
	at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
	at java.base/java.lang.Thread.run(Thread.java:829)
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);

javax.imageio.IIOException: Can't read input file!
	at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
	at REPL.$JShell$42B$ImageConverter.main($JShell$42B.java:31)
	at REPL.$JShell$44.do_it$($JShell$44.java:22)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at io.github.spencerpark.ijava.execution.IJavaExecutionControl.lambda$execute$1(IJavaExecutionControl.java:95)
	at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
	at java.base/java.lang.Thread.run(Thread.java:829)

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);

javax.imageio.IIOException: Can't read input file!
	at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
	at REPL.$JShell$46$ImageScaler.main($JShell$46.java:37)
	at REPL.$JShell$47.do_it$($JShell$47.java:23)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at io.github.spencerpark.ijava.execution.IJavaExecutionControl.lambda$execute$1(IJavaExecutionControl.java:95)
	at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
	at java.base/java.lang.Thread.run(Thread.java:829)

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.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 = "/home/kaiden_do/vscode/kaidencsablog/images/Nikhil.png";
            String outputPath = "/home/kaiden_do/vscode/kaidencsablog/images/";

            // 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);

Image conversion successful!

Grading for Hacks

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