Java GUI program to convert 2D array value into graphic [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am a beginner in Java & i have to make a java program that takes the input from a 2d array with dimensions 347*697 (array's value range from 2200 to 4200 ). I have to do such that for every 100 increase in range there is a set of specific color(for e.g 2200-2300 color(214,217,223) & so on). I have never done anything .. & this is the program i found little bit similar ... Can anyone give me idea how to convert it
I know its too much to ask for , but tomorrow i have to give a ppt. & when every option is closed i came here. Please guys, I need help badly
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class Map extends JPanel {
public static final Color CITY = new Color(214,217,223);
public static final Color DESERT = new Color(255,204,102);
public static final Color DIRT_ROAD = new Color(153,102,0);
public static final Color FOREST = new Color(0,102,0);
public static final Color HILLS = new Color(51,153,0);
public static final Color LAKE = new Color(0,153,153);
public static final Color MOUNTAINS = new Color(102,102,255);
public static final Color OCEAN = new Color(0,0,153);
public static final Color PAVED_ROAD = new Color(51,51,0);
public static final Color PLAINS = new Color(102,153,0);
public static final Color[] TERRAIN = {
CITY,
DESERT,
DIRT_ROAD,
FOREST,
HILLS,
LAKE,
MOUNTAINS,
OCEAN,
PAVED_ROAD,
PLAINS
};
public static final int NUM_ROWS = 215;
public static final int NUM_COLS = 300;
public static final int PREFERRED_GRID_SIZE_PIXELS = 10;
// In reality you will probably want a class here to represent a map tile,
// which will include things like dimensions, color, properties in the
// game world. Keeping simple just to illustrate.
private final Color[][] terrainGrid;
public Map(){
this.terrainGrid = new Color[NUM_ROWS][NUM_COLS];
Random r = new Random();
// Randomize the terrain
for (int i = 0; i < NUM_ROWS; i++) {
for (int j = 0; j < NUM_COLS; j++) {
int randomTerrainIndex = r.nextInt(TERRAIN.length);
Color randomColor = TERRAIN[randomTerrainIndex];
this.terrainGrid[i][j] = randomColor;
}
}
int preferredWidth = NUM_COLS * PREFERRED_GRID_SIZE_PIXELS;
int preferredHeight = NUM_ROWS * PREFERRED_GRID_SIZE_PIXELS;
setPreferredSize(new Dimension(preferredWidth, preferredHeight));
}
#Override
public void paintComponent(Graphics g) {
// Important to call super class method
super.paintComponent(g);
// Clear the board
g.clearRect(0, 0, getWidth(), getHeight());
// Draw the grid
int rectWidth = getWidth() / NUM_COLS;
int rectHeight = getHeight() / NUM_ROWS;
for (int i = 0; i < NUM_ROWS; i++) {
for (int j = 0; j < NUM_COLS; j++) {
// Upper left corner of this terrain rect
int x = i * rectWidth;
int y = j * rectHeight;
Color terrainColor = terrainGrid[i][j];
g.setColor(terrainColor);
g.fillRect(x, y, rectWidth, rectHeight);
}
}
}
public static void main(String[] args) {
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Game");
Map map = new Map();
frame.add(map);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}

Create a byte[] with the rgb values for each pixel of the image you want. The byte[] length will be width * height * 3 (3 values for each pixel). Look at this for an example of how create a BufferedImage from the byte[].
Another alternative is to create a BufferedImage and set the rgb value for each pixel directly. In this case, you have to bit twiddle all 3 rgb values into a single int value.

Related

Why does my GUI of smiley faces appear to be one color instead of all elements having their own separate, random colors?

I'm attempting to draw these smiley faces out on a GUI and for their parts (eyes, smile, etc.) to be all random colors. However, when I use the setColor method for my variables, they all blend in with each other and I can't see the eyes, etc. Here is my code:
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class Smiley extends JPanel {
//declare required variable
//set the width of window
public static final int w = 400;
//set the height of window
public static final int h = 400;
//assign face diameter
public static final int fd = 180;
//initializes the face of x position
public static final int xp = 10;
//initializes the face of y position
public static final int yp = 10;
//initializes the width of eye
public static final int we = 20;
//initializes the height of eye
public static final int he = 20;
//set the Right eye's position on the x and y
public static final int xre = xp + 40;
public static final int yre = yp + 60;
//set the left eye's position on the x and y
public static final int xle = xp + 120;
public static final int yle = yp + 60;
//initialzes the width and height of the mouth
public static final int mw = 80;
public static final int mh = 50;
//initializes the x and y position of mouth on the face
public static final int xm = xp + 50;
public static final int ym = yp + 90;
//define the class variables of type Color
public Color profile, nface, fsmile, eye;
// Smiley constructor takes parameters for 4 colors that will be
public Smiley(Color profile, Color nface, Color fsmile, Color eye) {
//set the layout
setLayout(new BorderLayout());
//initialize the parameters
this.profile = profile;
this.nface = nface;
this.fsmile = fsmile;
this.eye = eye;
//call paint() method
repaint();
}
public void paintComponent(Graphics gr) {
super.paintComponent(gr);
Random random = new Random();
Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
gr.setColor(color);
profile = color;
nface = color;
fsmile = color;
eye = color;
//set the color of profile of the face
gr.setColor(profile);
//draw the face
gr.fillOval(xp, yp, fd + 7, fd + 7);
//fill the color of face
gr.setColor(nface);
gr.fillOval(xp + 3, yp + 3, fd, fd);
//fill the eye color
gr.setColor(eye);
//for draw right eye
gr.fillOval(xre, yre, we, he);
gr.setColor(eye);
//for draw left eye
gr.fillOval(xle, yle, we, he);
//for smile color
gr.setColor(fsmile);
gr.drawArc(xm, ym, mw, mh, 180, 180);
}
}
What I expect is something like this:
https://imgur.com/a/7hFGzw1
How would I go about achieving this?
And this is the code where I will implement the smileys:
import java.awt.*;
import java.awt.event.*; //determined to be useless and got rid of
actionPerformed method
import javax.swing.*;
public class SmileyGrid extends JFrame {
//object for SmileGrid class
static SmileyGrid gs = new SmileyGrid();
public static void main(String[] args) {
gs.setSize(800, 800);
gs.setLayout(new GridLayout(3, 3));
//call createFace function()
gs.createGUI();
gs.setVisible(true);
}
public SmileyGrid() {
}
private void createGUI() {
for (int a = 0; a < 9; a++) {
Smiley sp = new Smiley(Color.BLUE, Color.YELLOW, Color.RED, Color.black);
gs.add(sp);
}
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Here:
profile = color;
nface = color;
fsmile = color;
These are supposed to be your 3 different colors. But you initialize all three to the same value! Instead, you would have to call the random function 3 times. Or to be precise: you should invoke that function repeatedly until your 3 colors are really different.
Alternatively: you could define 3 sets, each with 5, 10 different colors manually upfront. And then your code picks a random color from each set. Meaning: instead of using totally random colors, you could select sets of colors that always work together when mixed.
Welcome to SO. You are assigning the same Color object to all your variables so naturally they have the same color. You'll need to generate new random colors for each of them rather than assigning color to all of them.
profile = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
...

How to make and draw a Perlin Noise on a JPanel [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to make a application that draws a noise to a JPanel in Java. I came up with a really random noise, but i would like to draw a Perlin or Simplex Noise.
Here is the code:
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class Paint extends JPanel {
private static boolean running = false;
private static Paint paint = new Paint();
private static Random random = new Random();
public static void main(String args[]) {
running = true;
JFrame f = new JFrame();
f.setSize(800, 800);
f.setResizable(running);
f.setUndecorated(running);
f.setLocationRelativeTo(null);
f.add(paint);
f.setVisible(running);
while(running) {
paint.repaint();
}
}
public void paint(Graphics g) {
noise(g);
}
private void noise(Graphics g) {
for(int i = 0; i < 800; i=i+10) {
for(int j = 0; j < 800; j=j+10) {
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
g.fillRect(j, i, 10, 10);
}
}
running = false;
}
}
So how would I implant the Perlin Noise algorithm to this code, while not having to install external libraries.
EDIT: I am not lazy, or something. I read my way through all possible Noise generations, I just don't completely understand how to immigrate the noise methods into the class.
You are lucky, I recently did exactly this, heres my code:
BufferedImage tex;
float[] interpol;
int size;
float[] noise;
float[] workSet;
float r1,g1,b1,r2,g2,b2;
int octaves=4;
int octaveOffset=2;
public void init(int size)
{
this.size=size;
tex=new BufferedImage(size,size,BufferedImage.TYPE_INT_ARGB);
interpol=new float[size];
workSet=new float[size*size];
noise=new float[size*size];
float smult=(float) (Math.PI/size);
for(int i=0;i<size;i++)
{
interpol[i]=(1+(float) Math.cos(i*smult))/2;
}
r1=255;
g1=255;
b1=255;
r2=0;
g2=0;
b2=0;
}
public void generate()
{
Random r=new Random();
int[] pix=((DataBufferInt)(tex.getRaster().getDataBuffer())).getData();
int totalSize=size*size;
for(int i=0;i<totalSize;i++)
{
noise[i]=0.5f;
}
float[] randoms=new float[(size+1)*(size+1)];
int scale=size>>octaveOffset;
float max=0.50f;
for(int oct=0;oct<octaves;oct++)
{
int randsPerLine=size/scale+1;
int rands=randsPerLine*randsPerLine;
for(int i=0;i<rands;i++)
{
randoms[i]=max*(r.nextFloat()-0.5f);
}
for(int i=0;i<totalSize;i++)
{
int y=(i/size)/scale;
int suby=(i/size)%scale;
int x=(i%size)/scale;
int subx=(i%size)%scale;
float intp=interpol[subx*(size/scale)];
float colorA=randoms[y*randsPerLine+x]*intp+(1-intp)*randoms[y*randsPerLine+x+1];
float colorB=randoms[(1+y)*randsPerLine+x]*intp+(1-intp)*randoms[(1+y)*randsPerLine+x+1];
intp=interpol[suby*(size/scale)];
workSet[i]=colorA*intp+(1-intp)*colorB;
}
for(int i=0;i<totalSize;i++)
{
noise[i]+=workSet[i];
}
max/=2;
scale/=2;
}
for(int i=0;i<totalSize;i++)
{
int red=(int) (r1*noise[i]+r2*(1-noise[i]));
int g=(int) (g1*noise[i]+g2*(1-noise[i]));
int b=(int) (b1*noise[i]+b2*(1-noise[i]));
pix[i]=(255<<24)+(red<<16)+(g<<8)+b;
}
}
To draw it use g.drawImage(tex,[your coordinates],null).
My code generates a square image size x size with a noisy mixture between two colors, currently black and white, this can be changed by modifying r1, g1, b1, r2, g2, b2. Play around with the octaves and the octaveOffset values to make the noise suit your needs.
I only tested this code with size being a power of 2 and while merging with your code I found out that it only works if paint.init(1024) and paint.generate() are called right at the beginning of main().

Why doesn't my GUI show squares after repaint()? [duplicate]

I posted this question a bit earlier and was told to make it SSCCE so here goes (if I can make any improvements feel free to let me know):
I'm wondering why when my button "confirm" is clicked the old squares disappear and the redrawn squares do not appear on my GUI (made with swing). The Squares class draws 200 spaced out squares with an ID (0, 1, 2, or 3 as String) inside obtained from a different class (for the purpose of this question, let's assume it is always 0 and not include that class). For clarification: Squares draws everything perfectly the first time (also retrieves the correct IDs), but I want it to redraw everything once the button is clicked with new IDs.
Code for Squares:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.ArrayList;
public class Squares extends JPanel{
private ArrayList<Rectangle> squares = new ArrayList<Rectangle>();
private String stringID = "0";
public void addSquare(int x, int y, int width, int height, int ID) {
Rectangle rect = new Rectangle(x, y, width, height);
squares.add(rect);
stringID = Integer.toString(ID);
if(ID == 0){
stringID = "";
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
FontMetrics fm = g2.getFontMetrics();
int fontAscent = fm.getAscent();
g2.setClip(new Rectangle(0,0,Integer.MAX_VALUE,Integer.MAX_VALUE));
for (Rectangle rect : squares) {
g2.drawString(stringID, rect.x + 7, rect.y + 2 + fontAscent);
g2.draw(rect);
}
}
}
Code for GUI:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUIReserver extends JFrame implements Runnable{
private int myID;
private JButton confirm = new JButton("Check Availability and Confirm Reservation");
private JFrame GUI = new JFrame();
private Squares square;
public GUIReserver(int i) {
this.myID = i;
}
#Override
public void run() {
int rows = 50;
int seatsInRow = 4;
confirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
GUI.getContentPane().remove(square);
square = new Squares();
int spaceNum = 0;
int rowNum = 0;
int offsetX = 200;
int offsetY = 0;
for(int i = 0; i < rows * seatsInRow; i++){
square.addSquare(rowNum * 31 + offsetX,spaceNum * 21 + 50 + offsetY,20,20, 0); //normally the 4th parameter here would retrieve the ID from the main class
rowNum++;
if(rowNum == 10){
rowNum = 0;
spaceNum++;
}
if(spaceNum == 2){
spaceNum = 3;
rowNum = 0;
}
if(spaceNum == 5){
spaceNum = 0;
offsetY += 140;
}
}
GUI.getContentPane().add(square); //this does not show up at all (could be that it wasn't drawn, could be that it is out of view etc...)
GUI.repaint(); //the line in question
}
});
GUI.setLayout(new FlowLayout());
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setLocation(0,0);
GUI.setExtendedState(JFrame.MAXIMIZED_BOTH);
square = new Squares();
int spaceNum = 0;
int rowNum = 0;
int offsetX = 200;
int offsetY = 0;
for(int i = 0; i < rows * seatsInRow; i++){
square.addSquare(rowNum * 31 + offsetX,spaceNum * 21 + 50 + offsetY,20,20, 0); //normally the 4th parameter here would retrieve the ID from the main class
rowNum++;
if(rowNum == 10){
rowNum = 0;
spaceNum++;
}
if(spaceNum == 2){
spaceNum = 3;
rowNum = 0;
}
if(spaceNum == 5){
spaceNum = 0;
offsetY += 140;
}
}
GUI.getContentPane().add(square); //this shows up the way I wish
GUI.add(confirm);
GUI.pack();
GUI.setVisible(true);
}
}
Code for main:
public class AircraftSeatReservation {
static AircraftSeatReservation me = new AircraftSeatReservation();
private final int rows = 50;
private final int seatsInRow = 4;
private int seatsAvailable = rows * seatsInRow;
private Thread t3;
public static void main(String[] args) {
GUIReserver GR1 = new GUIReserver(3);
me.t3 = new Thread(GR1);
me.t3.start();
}
}
One major problem: Your Squares JPanels preferred size is only 20 by 20, and will likely actually be that size since it seems to be added to a FlowLayout-using container. Next you seem to be drawing at locations that are well beyond the bounds of this component, and so the drawings likely will never be seen. Consider allowing your Squares objects to be larger, and make sure to only draw within the bounds of this component.
Note also there is code that doesn't make sense, including:
private int myID;
private JTextField row, column, instru draft saved // ???
package question2;ction1, instruction2, seatLabel, rowLabel; // ???
I'm guessing that it's
private int myID;
private JTextField row, column, instruction1, instruction2, seatLabel, rowLabel;
And this won't compile for us:
int rows = AircraftSeatReservation.getRows();
int seatsInRow = AircraftSeatReservation.getSeatsInRow(); // and shouldn't this take an int row parameter?
since we don't have your AircraftSeatReservation class (hopefully you don't really have static methods in that class).
And we can't compile or run your current code. We don't want to see your whole program, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem. So as Andrew Thompson recommends, for better help, please create and post your Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example.
I would try to OOP-ify your problem as much as possible, to allow you to divide and conquer. This could involve:
Creating a SeatClass enum, one with possibly two elements, FIRST and COACH.
Creating a non-GUI Seat class, one with several fields including possibly: int row, char seat ( such as A, B, C, D, E, F), a SeatClass field to see if it is a first class seat or coach, and a boolean reserved field that is only true if the seat is reserved.
This class would also have a getId() method that returns a String concatenation of the row number and the seat char.
Creating a non-GUI Airplane class, one that holds two arrays of Seats, one for SeatClass.FIRST or first-class seats, and one for SeatClass.COACH.
It would also have a row count field and a seat count (column count) field.
After creating all these, then work on your GUI classes.
I'd create a GUI class for Seats, perhaps GuiSeat, have it contain a Seat object, perhaps have it extend JPanel, allow it to display its own id String that it gets from its contained Seat object, have it override getBackground(...) so that it's color will depend on whether the seat is reserved or not.
etc.....

Set red 2d array values using for loop

I am trying to create a method that will get all of the red values in an image and display only the red values. I am having trouble with my getRedImage() method. I am new to this and any help would be much appreciated!
public class SimpleRGB
{
private int width, height;
private int[][] red = new int[1000][1000];
This part gets the red value and sets it to the specified position of my 2D red array:
public void setRed(int x, int y, int aRed)
{
red[x][y] = aRed;
}
This part gets the red value at coordinate (x,y) and returns it:
public int getRed(int x, int y)
{
int thisr = red[x][y];
return thisr;
}
I am unsure of how to phrase this part. I know I need to create a new SimpleRGB object to return, and then use nested for-loops to set the red 2D array of my new simple RGB oject to the red 2D array of this simpleRGB object, and then use a nested for loop to set both the green and blue 2D array values to all zero. I am just unsure of how to do this.
public SimpleRGB getRedImage()
{
// This is where I am confused.
}
}
Looping in 2d array is easy
But i don't think this is the right way.
private int[][] red = new int[1000][1000];
for (int i = 0; i < 1000; i++) {
for(int j = 0; j < 1000; j++) {
System.out.println(red[i][j]);
}
}
I did not understand very well your question, but, if you have 3 2D arrays, one for each RGB:
int[][] red = new int[1000][1000];
int[][] green = new int[1000][1000];
int[][] blue = new int[1000][1000];
and you only want the red color in the image, just set to zero all other colors:
public class SimpleRGB
{
private int width;
private int height;
private int[][] red = new int[1000][1000];
private int[][] green = new int[1000][1000];
private int[][] blue = new int[1000][1000];
public SimpleRGB(int[][] red, int[][] green, int[][] blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
// some methods
public int[][] getRed() {
return red;
}
public int[][] getGreen() {
return green;
}
public int[][] getBlue() {
return blue;
}
// the method that interests you
public SimpleRGB getRedImage() {
return new SimpleRGB(red, new int[1000][1000], new int[1000][1000]);
}
}
Creating a new array, all its elements are initialized by default to 0.
I finally figured it out:
public SimpleRGB getRedImage()
{
SimpleRGB redImage = new SimpleRGB(width, height);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
redImage.setRed(i, j, getRed(i, j));
redImage.setGreen(i, j, getGreen(i, j, 0);
redImage.setBlue(i, j, getBlue(i, j, 0));
}
}
return redImage;
}
I had the basic structure correct but I was altering THIS red/green/blue instead of adding redImage.setRed to modify the NEW object.

How do I flip an image upside-down?

I was wondering if I could find some help on this problem. I was asked to use an image ("corn.jpg"), and flip it entirely upside down. I know I need to write a program which will switch pixels from the top left corner with the bottom left, and so on, but I wasn't able to get my program to work properly before time ran out. Could anyone provide a few tips or suggestions to solve this problem? I'd like to be able to write my code out myself, so suggestions only please. Please note that my knowledge of APImage and Pixel is very limited. I am programming in Java.
Here is what I managed to get done.
import images.APImage;
import images.Pixel;
public class Test2
{
public static void main(String [] args)
{
APImage image = new APImage("corn.jpg");
int width = image.getImageWidth();
int height = image.getImageHeight();
int middle = height / 2;
//need to switch pixels in bottom half with the pixels in the top half
//top half of image
for(int y = 0; y < middle; y++)
{
for (int x = 0; x < width; x++)
{
//bottom half of image
for (int h = height; h > middle; h++)
{
for(int w = 0; w < width; w++)
{
Pixel bottomHalf = image.getPixel(h, w);
Pixel topHalf = image.getPixel(x, y);
//set bottom half pixels to corresponding top ones?
bottomHalf.setRed(topHalf.getRed());
bottomHalf.setGreen(topHalf.getGreen());
bottomHalf.setBlue(topHalf.getBlue());
//set top half pixels to corresponding bottom ones?
topHalf.setRed(bottomHalf.getRed());
topHalf.setGreen(bottomHalf.getGreen());
topHalf.setBlue(bottomHalf.getBlue());
}
}
}
}
image.draw();
}
}
Thank you for your help!
See Transforming Shapes, Text, and Images.
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class FlipVertical {
public static BufferedImage getFlippedImage(BufferedImage bi) {
BufferedImage flipped = new BufferedImage(
bi.getWidth(),
bi.getHeight(),
bi.getType());
AffineTransform tran = AffineTransform.getTranslateInstance(0, bi.getHeight());
AffineTransform flip = AffineTransform.getScaleInstance(1d, -1d);
tran.concatenate(flip);
Graphics2D g = flipped.createGraphics();
g.setTransform(tran);
g.drawImage(bi, 0, 0, null);
g.dispose();
return flipped;
}
FlipVertical(BufferedImage bi) {
JPanel gui = new JPanel(new GridLayout(1,2,2,2));
gui.add(new JLabel(new ImageIcon(bi)));
gui.add(new JLabel(new ImageIcon(getFlippedImage(bi))));
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) throws AWTException {
final Robot robot = new Robot();
Runnable r = new Runnable() {
#Override
public void run() {
final BufferedImage bi = robot.createScreenCapture(
new Rectangle(0, 660, 200, 100));
new FlipVertical(bi);
}
};
SwingUtilities.invokeLater(r);
}
}
Whenever you're swapping variables, if your language doesn't allow for simultaneous assignment (and Java doesn't), you need to use a temporary variable.
Consider this:
a = 1;
b = 2;
a = b; // a is now 2, just like b
b = a; // b now uselessly becomes 2 again
Rather than that, do this:
t = a; // t is now 1
a = b; // a is now 2
b = t; // b is now 1
EDIT: And also what #vandale says in comments :P
If you are able to use the Graphics class, the following may be of use:
http://www.javaworld.com/javatips/jw-javatip32.html
And the Graphics class documentation:
http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html
Instead of using
Pixel bottomHalf = image.getPixel(h, w);
Pixel topHalf = image.getPixel(x, y);
//set bottom half pixels to corresponding top ones?
bottomHalf.setRed(topHalf.getRed());
bottomHalf.setGreen(topHalf.getGreen());
bottomHalf.setBlue(topHalf.getBlue());
//set top half pixels to corresponding bottom ones?
topHalf.setRed(bottomHalf.getRed());
topHalf.setGreen(bottomHalf.getGreen());
topHalf.setBlue(bottomHalf.getBlue());
You should have stored the bottomHalf's RGB into a temporary Pixel and used that to set topHalf after replacing bottomHalf's values (if you follow). You could have also really used something like this.... assuming your pixel operates on integer rgb values (which would have improved your main method).
private static final Pixel updateRGB(Pixel in, int red, int green, int blue) {
in.setRed(red); in.setGreen(green); in.setBlue(blue);
}
You want to flip the image upside down, not swap the top and bottom half.
The loop could look like this.
int topRow = 0;
int bottomRow = height-1;
while(topRow < bottomRow) {
for(int x = 0; x < width; x++) {
Pixel t = image.getPixel(x, topRow);
image.setPixel(x, topRow, image.getPixel(x, bottomRow));
image.setPixel(x, bottomRow, t);
}
topRow++;
bottomRow--;
}

Categories