将图像复制到特定坐标
问题描述:
我有一个运行良好的程序;但是,我希望能够将地球图像复制到创建的新图像的不同部分。例如,如果我可以将地球图片放在左下角而不是左上角。将图像复制到特定坐标
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(800,800);
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
因此,如果有人能请说明如何修改这个代码来获取地球的图片在左下角显示为新的目标图像上的例子,将不胜感激!谢谢!
答
如果我可以将地球图片放在左下角而不是左上角。
做适当的数学运算以抵消坐标 - 例如移动到左下角,您需要垂直偏移目标像素 - 换句话说,将目标像素的y值偏移目标高度减去源的高度
int vOffset = targetPicture1.getHeight() - sourcePicture.getHeight();
//
targetPixel = targetPicture1.getPixel(x, vOffset + y);
什么是'Picture'? – copeg
只需要创建一个图片对象。类似于int如何用于整数,或者String如何用于字符串。这仅用于创建的图片。 –
好的,那么什么名称空间是'图片'? –