前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java实现多张图片合并一张

Java实现多张图片合并一张

作者头像
程序员云帆哥
发布2022-05-12 11:05:30
1.7K0
发布2022-05-12 11:05:30
举报
文章被收录于专栏:程序员云帆哥

Java实现多张图片合并一张,这个还是挺常用到的。

代码语言:javascript
复制
public class ImageUtil {
    public static boolean merge(String[] imgs, String type, String mergePic) {
        int dstHeight = 0;
        int dstWidth = 0;
        // 获取需要拼接的图片长度
        int len = imgs.length;
        // 判断长度是否大于0
        if (len < 1) {
            return false;
        }
        File[] file = new File[len];
        BufferedImage[] images = new BufferedImage[len];
        int[][] ImageArrays = new int[len][];
        for (int i = 0; i < len; i++) {
            try {
                file[i] = new File(imgs[i]);
                images[i] = ImageIO.read(file[i]);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            int width = images[i].getWidth();
            int height = images[i].getHeight();

            // 从图片中读取RGB 像素
            ImageArrays[i] = new int[width * height];
            ImageArrays[i] = images[i].getRGB(0, 0, width, height, ImageArrays[i], 0, width);

            // 计算合并的宽度和高度
            dstWidth = dstWidth > width ? dstWidth : width;
            dstHeight += height;
        }

        // 合成图片像素
        System.out.println("宽度:" + dstWidth);
        System.out.println("高度:" + dstHeight);

        if (dstHeight < 1) {
            System.out.println("dstHeight < 1");
            return false;
        }
        // 生成新图片
        try {
            BufferedImage imageNew = new BufferedImage(dstWidth, dstHeight, BufferedImage.TYPE_INT_RGB);
            int width_i = 0;
            int height_i = 0;
            for (int i = 0; i < images.length; i++) {
                int width = images[i].getWidth();
                int height = images[i].getHeight();
                imageNew.setRGB(0, height_i, width, height, ImageArrays[i], 0, width);
                height_i += height;
            }

            File outFile = new File(mergePic);
            // 写图片,输出到硬盘
            ImageIO.write(imageNew, type, outFile);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void main(String[] args) throws Exception {
        String saveFile = "E:\\tmp\\avatar2.png";
        String images[] = {"E:\\tmp\\avatar.png", "E:\\tmp\\avatar.png"};
        ImageUtil.merge(images, "png", saveFile);
    }
}

效果如下:

在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-10-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档