Search code examples
javaimagecolorscoordinatesbluej

Change an image's coordinates across a background Java


I am working on this code, but I am struggling to figure out how to change the coordinates of an image, in this case, a picture of the earth, in the targetPicture1 (background).

import java.awt.*;
public class CopyCatDemo
{
 public static void main(String[] args)
 {
    Picture sourcePicture = new Picture("earth.jpg");
    System.out.println("Width: " + sourcePicture.getWidth());
    System.out.println("Height: " + sourcePicture.getHeight());
    Picture targetPicture1 = new Picture(400,400);
    targetPicture1.setAllPixelsToAColor(Color.BLACK);

    Pixel sourcePixel, targetPixel = null;
    Color sourceColor, targetColor = null;

    for(int y = 0; y < sourcePicture.getHeight(); y++)
    {
        for(int x = 0; x < sourcePicture.getWidth(); x++)
        {
            sourcePixel = sourcePicture.getPixel(x,y);
            sourceColor = sourcePixel.getColor();
            targetPixel = targetPicture1.getPixel(x,y);
            targetPixel.setColor(sourceColor);         
        }
    }

    sourcePicture.show();
    targetPicture1.show();
    targetPicture1.write("NewFile.jpg");
 }//end of main method
}//end of class

Solution

  • I would recommend you use an offset. This way you can dictate where the image will be places when you copy it over.

    try something like:

    import java.awt.*;
    public class CopyCatDemo
    {
     public static void main(String[] args)
     {
        Picture sourcePicture = new Picture("earth.jpg");
        System.out.println("Width: " + sourcePicture.getWidth());
        System.out.println("Height: " + sourcePicture.getHeight());
        Picture targetPicture1 = new Picture(400,400);
        targetPicture1.setAllPixelsToAColor(Color.BLACK);
    
        int offsetX = 0;
        int offsetY = 0;
    
        Pixel sourcePixel, targetPixel = null;
        Color sourceColor, targetColor = null;
    
        for(int y = 0; y < sourcePicture.getHeight(); y++)
        {
            for(int x = 0; x < sourcePicture.getWidth(); x++)
            {
                sourcePixel = sourcePicture.getPixel(x,y);
                sourceColor = sourcePixel.getColor();
                targetPixel = targetPicture1.getPixel(offsetX + x, offsetY + y);
                targetPixel.setColor(sourceColor);         
            }
        }
    
        sourcePicture.show();
        targetPicture1.show();
        targetPicture1.write("NewFile.jpg");
     }//end of main method
    }//end of class
    

    then lets say you wanted the image to be located in the bottom right of the screen. Simply set you offset accordingly:

    int offsetX = 400 - sourcePicture.getWidth();
    int offsetY = 400 - sourcePicture.getHeight();
    

    Then the image will start being drawn its width a height away from the bottom right corner of the screen.