Search code examples
javaimagepixelimage-resizing

Resizing an image in java by factor of 2


This is what I have so far, but don't know what to do now? It makes the picture bigger but there is a lot of spaces in the picture. How do you copy pixels to fill in the holes?

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;
}

Solution

  • Well if you enlarge an image times two, and you don't use interpolation. Then a pixel (x,y) of the original image, should be mapped to pixels (2*x,2*y), (2*x,2*y+1), (2*x+1,2*y) and (2*x+1,2*y+1). So the algorithm should be:

    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);
            for(int x2 = 2*x; x2 < 2*x+2; x2++) {
                for(int y2 = 2*y; y2 < 2*y+2; y2++) {
                    enlarged.getPixel(x2,y2).setColor(orig.getColor());
                }
            }
        }
    }

    Or more generic, with a magnification parameter mag:

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