Java单个图片切分成多个并且加入白色分隔条合成全新的图片

该代码实现将一张图片按比例切分为3份,并在每两份之间插入分割图片,然后将切分后的图片像素存入二维数组,最后合成新图片。主要涉及到BufferedImage、ImageIO、Thumbnails等类的使用,以及图片的读取、子图获取、像素存取和合成操作。
摘要由CSDN通过智能技术生成

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);
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Acmen-zym

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值