Java 图片合并

@Test
public void test() throws IOException {
//获得图片地址
URL img = new URL("https://mmbiz.qpic.cn/mmbiz_png/RXXibAPt2Zu9NtJZeBREaKHiajDF0ze7vfzgF36pBm66xObG1GN577qG5Eeb37UAl2VvDYzmgWj0sjLAkgSGianiaw/640?wx_fmt=bmp");
//获得图片输入流
InputStream in = img.openStream();
BufferedImage image= ImageIO.read(in);

URL img2 = new URL("https://mmbiz.qpic.cn/mmbiz_png/RXXibAPt2Zu9NtJZeBREaKHiajDF0ze7vfxrDhjwNxJIF3e6lO7pvPpZ1cCNEYUUX1T1AsC9V2RwdibWP2w87DDKQ/640?wx_fmt=bmp");
InputStream in2 = img2.openStream();
BufferedImage image2= ImageIO.read(in2);

BufferedImage bufferedImage = mergeImage(true, image, image2);

in.close();
in2.close();
}

/**
 * 合并任数量的图片成一张图片
 *
 * @param isHorizontal
 *            true代表水平合并,fasle代表垂直合并
 * @param imgs
 *            待合并的图片数组
 * @return
 * @throws IOException
 */
private BufferedImage mergeImage(boolean isHorizontal, BufferedImage... imgs) throws IOException {
    // 生成新图片
    BufferedImage destImage = null;
    // 计算新图片的长和高
    int allw = 0, allh = 0, allwMax = 0, allhMax = 0;
    // 获取总长、总宽、最长、最宽
    for (int i = 0; i < imgs.length; i++) {
        BufferedImage img = imgs[i];
        allw += img.getWidth();
        allh += img.getHeight();
        if (img.getWidth() > allwMax) {
            allwMax = img.getWidth();
        }
        if (img.getHeight() > allhMax) {
            allhMax = img.getHeight();
        }
    }
    // 创建新图片
    if (isHorizontal) {
        destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
    } else {
        destImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);
    }
    // 合并所有子图片到新图片
    int wx = 0, wy = 0;
    for (int i = 0; i < imgs.length; i++) {
        BufferedImage img = imgs[i];
        int w1 = img.getWidth();
        int h1 = img.getHeight();
        // 从图片中读取RGB
        int[] ImageArrayOne = new int[w1 * h1];
        ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中
        if (isHorizontal) { // 水平方向合并
            destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
        } else { // 垂直方向合并
            destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
        }
        wx += w1;
        wy += h1;
    }
    return destImage;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值