Java replacing the background of an image

832 views Asked by At

I am writing a program where I take one picture and replace the background of that picture.

The picture I have is:

black cat with white background

And the background that I am using for the cat is:

shiny galaxy background

I know that in order to this I have to use the cat picture and take the color pixels that are less than 255 because the red, green, and blue values for white are 255. So then I take those pixels that are less than 255, which make up the cat, and place it on the background picture in the same X and Y positions. The problem I am having is that I can not figure out how to code this to get it to work.

I have the basic code which is:

import java.awt.*;
public class TrueColors
{

   public static void main(String [] args) 
   {
       Picture pictureObj2 = new Picture("9.01 cat picture.jpg");
       pictureObj2.explore();
       int redValue = 0; int greenValue = 0; int blueValue = 0;

       Pixel targetPixel = new Pixel(pictureObj2, 0, 0);
       Color pixelColor = null;

       for(int y = 0; y < pictureObj2.getHeight(); y++)
       {
           for(int x = 0; x < pictureObj2.getWidth(); x++)
           {
               targetPixel = pictureObj2.getPixel(x,y);
               pixelColor = targetPixel.getColor();

               redValue = pixelColor.getRed();
               greenValue = pixelColor.getGreen();
               blueValue = pixelColor.getBlue();

               pixelColor = new Color(redValue, greenValue, blueValue);
               targetPixel.setColor(pixelColor);

           }
       }

       pictureObj2.explore();
       pictureObj2.write("ColoredCat.jpg");
       pictureObj2.show();

   }   
}

I was just wondering if you could help me figure out how to take the concept of this program that I understand and turn it into code

Thank you

1

There are 1 answers

0
River On BEST ANSWER

What you have is almost correct. Simply read in your second picture like you have your first picture here:

Picture background = new Picture("background.png");
background.explore();

Then in your inner loop simply do:

targetPixel = pictureObj2.getPixel(x,y);
pixelColor = targetPixel.getColor();

if(!pixelColor.equals(WHITE)) //test if you have a blank pixel
    background.getPixel(x,y).setColor(pixelColor); //if not its a cat pixel so add it on top of the background