1、将一个完整的图片切分成3张放入imageList集合中,然后在每个图片后面加上分割图片 partition.jpg。
2、将imageList中图片像素存入对应的二维数组ImageArrays中,并且计算合成新图片的总高度imageCountHeight
3、创建一个imageNew 的图片缓冲流,然后在setRGB方法中设置图片高度宽度以及二维数组保存的像素
public void imageTest() throws IOException {
FileImageInputStream fileImageInputStream = new FileImageInputStream(new File("C:\\Users\\Administrator.USER-20190722MT\\Desktop\\test.jpg"));
BufferedImage image = ImageIO.read(fileImageInputStream);
int height = image.getHeight() / 3;
int width = image.getWidth();
//用来保存使用image.getSubimage方法切割的图片,和分割白条图片partition.jpg
List<BufferedImage> imageList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
int ch = height * i;//代表Y轴
if (imageList.size() > 0) {//设置分割图片
Resource resource = new ClassPathResource("static\\img\\partition.jpg");
InputStream inputStream = resource.getInputStream();
BufferedImage partitionImage = ImageIO.read(inputStream);
partitionImage = Thumbnails.of(partitionImage).size(width, partitionImage.getHeight()).asBufferedImage();
imageList.add(partitionImage);
}
BufferedImage subImage = image.getSubimage(0, ch, width, height);
imageList.add(subImage);
}
int[][] ImageArrays = new int[imageList.size()][];
int imageCountHeight = 0;//用来记录需要合成图片的总高度
for (int i = 0; i < imageList.size(); i++) {
imageList.set(i, Thumbnails.of(imageList.get(i)).width(width).asBufferedImage());
int subWidth = imageList.get(i).getWidth();
int subHeight = imageList.get(i).getHeight();
ImageArrays[i] = new int[subWidth * subHeight];
ImageArrays[i] = imageList.get(i).getRGB(0, 0, width, subHeight, ImageArrays[i], 0, width);
imageCountHeight += subHeight;
}
BufferedImage imageNew = new BufferedImage(width, imageCountHeight, BufferedImage.TYPE_INT_RGB);
int localHeight = 0;//当前循环合成图片的高度
for (int i = 0; i < imageList.size(); i++) {
int height1 = imageList.get(i).getHeight();
imageNew.setRGB(0, localHeight, width, height1, ImageArrays[i], 0, width);
localHeight += imageList.get(i).getHeight();
}
File outFile = new File("C:\\Users\\Administrator.USER-20190722MT\\Desktop\\subImage.jpg");
ImageIO.write(imageNew, "jpg", outFile);
}