How to merge multiple images into one image - Java ImageIO

    技术2022-05-19  23

    My previous post shows how to split an image into chunks. Now let's see how to merge multiple images into one image. Say we need to concatenate following four image chunks. I got these chunks by splitting the image in the right hand side, using the image splitter.

      Following code shows how to concatenate the image chunks above into one image.  view plain print ? int rows = 2;   //we assume the no. of rows and cols are known and each chunk has equal width and height          int cols = 2;          int chunks = rows * cols;            int chunkWidth, chunkHeight;          int type;          //fetching image files          File[] imgFiles = new File[chunks];          for (int i = 0; i < chunks; i++) {              imgFiles[i] = new File("archi" + i + ".jpg");          }           //creating a bufferd image array from image files          BufferedImage[] buffImages = new BufferedImage[chunks];          for (int i = 0; i < chunks; i++) {              buffImages[i] = ImageIO.read(imgFiles[i]);          }          type = buffImages[0].getType();          chunkWidth = buffImages[0].getWidth();          chunkHeight = buffImages[0].getHeight();            //Initializing the final image          BufferedImage finalImg = new BufferedImage(chunkWidth*chunks, chunkHeight*chunks, type);            int num = 0;          for (int i = 0; i < rows; i++) {              for (int j = 0; j < cols; j++) {                  finalImg.createGraphics().drawImage(buffImages[num], chunkWidth * j, chunkHeight * i, null);                  num++;              }          }          System.out.println("Image concatenated.....");          ImageIO.write(finalImg, "jpeg"new File("finalImg.jpg"));   You might also like: How to Split an Image into Chunks - Java ImageIOHow to Replace Strings in Java - Using java.util.regex packageHow to Write a Custom Class Loader to Load Classes from a JarHow to Print from Java (JPS) - javax.print Package


    最新回复(0)