将 java 中的图像调整为 2 倍

Resizing an image in java by factor of 2

这是我目前拥有的,但不知道现在该怎么办?它使图片变大,但图片中有很多空间。如何复制像素来填充孔洞?

public Picture enlarge()
{
 Picture enlarged = new Picture(getWidth() * 2, getHeight() * 2);

for (int x = 0; x < getWidth(); x++)
{
  for (int y = 0; y < getHeight(); y++)
  {
    Pixel orig = getPixel(x,y);
    Pixel enlargedPix = enlarged.getPixel(x*2,y*2);
    Pixel enlargedPix2 = enlarged. getPixel(x,y);
    enlargedPix.setColor(orig.getColor());
    enlargedPix2.setColor(orig.getColor());
  }
}
return enlarged;
}

新图片中存在间隙的原因是因为您只为每个原始像素设置一次像素,而您必须为原始图像的每个像素设置 4 个像素(即 2x2),因为它是两次一样大。

好吧,如果你放大图像两倍,并且你不使用插值.那么原始图像的像素 (x,y) 应该映射到像素 (2*x,2*y)(2*x,2*y+1)(2*x+1,2*y)(2*x+1,2*y+1)。所以算法应该是:

Picture enlarged = new Picture(getWidth() * 2, getHeight() * 2);
for (int x = 0; x < getWidth(); x++) {
    for (int y = 0; y < getHeight(); y++) {
        Pixel orig = getPixel(x,y);
        <b>for(int x2 = 2*x; x2 < 2*x+2; x2++) {</b>
            <b>for(int y2 = 2*y; y2 < 2*y+2; y2++) {</b>
                enlarged.getPixel(<b>x2,y2</b>).setColor(orig.getColor());
            <b>}</b>
        <b>}</b>
    }
}

或更通用,带有放大参数 mag:

Picture enlarged = new Picture(getWidth() * <b>mag</b>, getHeight() * <b>mag</b>);
for (int x = 0; x < getWidth(); x++) {
    for (int y = 0; y < getHeight(); y++) {
        Pixel orig = getPixel(x,y);
        for(int x2 = <b>mag</b>*x; x2 < <b>mag</b>*x+<b>mag</b>; x2++) {
            for(int y2 = <b>mag</b>*y; y2 < <b>mag</b>*y+<b>mag</b>; y2++) {
                enlarged.getPixel(x2,y2).setColor(orig.getColor());
            }
        }
    }
}