实现内容
能够实现将四张图片拼接,整合成一张完整图片
使用了getRGB、setRGB方法进行图片的提取拼接
实现代码
image1 = ImageIO.read(imageFile1); image2 = ImageIO.read(imageFile2); image3 = ImageIO.read(imageFile3); image4 = ImageIO.read(imageFile4); int width12 = image1.getWidth() + image2.getWidth(); int width34 = image3.getWidth() + image4.getWidth(); int width = Math.max(width12, width34); int height = image1.getHeight() + image3.getHeight(); mergedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); int[] rgbArray1 = image1.getRGB(0, 0, image1.getWidth(), image1.getHeight(), null, 0, image1.getWidth()); int[] rgbArray2 = image2.getRGB(0, 0, image2.getWidth(), image2.getHeight(), null, 0, image2.getWidth()); int[] rgbArray3 = image3.getRGB(0, 0, image3.getWidth(), image3.getHeight(), null, 0, image3.getWidth()); int[] rgbArray4 = image4.getRGB(0, 0, image4.getWidth(), image4.getHeight(), null, 0, image4.getWidth()); // 创建四个线程,分别处理每张图片的RGB数组,使用四个线程,是考虑到可能图片操作速度慢,但是实际效果提升不是很大,可不用 ExecutorService executor = Executors.newFixedThreadPool(4); BufferedImage finalMergedImage = mergedImage; BufferedImage finalImage1 = image1; BufferedImage finalImage2 = image2; BufferedImage finalImage3 = image3; BufferedImage finalImage4 = image4; Future<Void> future1 = executor.submit(() -> { writeRGBArrayToMergedImage(rgbArray1, finalMergedImage, 0, 0, finalImage1.getWidth(), finalImage1.getHeight()); return null; }); Future<Void> future2 = executor.submit(() -> { writeRGBArrayToMergedImage(rgbArray2, finalMergedImage, finalImage1.getWidth(), 0, finalImage2.getWidth(), finalImage2.getHeight()); return null; }); Future<Void> future3 = executor.submit(() -> { writeRGBArrayToMergedImage(rgbArray3, finalMergedImage, 0, finalImage1.getHeight(), finalImage3.getWidth(), finalImage3.getHeight()); return null; }); Future<Void> future4 = executor.submit(() -> { writeRGBArrayToMergedImage(rgbArray4, finalMergedImage, finalImage3.getWidth(), finalImage1.getHeight(), finalImage4.getWidth(), finalImage4.getHeight()); return null; }); // 等待四个线程执行完毕 future1.get(); future2.get(); future3.get(); future4.get(); // 关闭线程池 executor.shutdown();
//------------------------------------------------------------------------
private static void writeRGBArrayToMergedImage(int[] rgbArray, BufferedImage mergedImage, int x, int y, int w, int h) {
mergedImage.setRGB(x, y, w, h, rgbArray, 0, w);
}