Loading

一段四合一图片整和Java代码

实现内容

能够实现将四张图片拼接,整合成一张完整图片

 使用了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);
}

补充

Q多线程操作finalMergedImage ,为什么最终获得的是整合后的值而没有被覆盖且没有冲突
 
A:这是因为在Java中,对象引用是传递的,而不是对象本身。在这段代码中,每个线程都是使用final修饰的变量引用了finalMergedImage,而finalMergedImage指向的是同一个BufferedImage对象。因此,每个线程都在对同一个对象进行操作,但是由于这些操作并不会修改这个对象的引用,因此不会出现竞争条件和冲突。最终获得的是整合后的值,因为每个线程都在对这个对象进行修改,最终将它们整合起来就得到了最终的结果。
posted @ 2023-03-21 16:32  李旭2018  阅读(75)  评论(0编辑  收藏  举报