java多张图片合成

image.drawImage这个方法是合成图片时,新的图片开始的类似x轴和y轴的开始的坐标,拥有抽象思维的大家好好捋一下.
本文的顺序都在注释里,大家可以改一下路径,在本地弄一下图片试一下
引入
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
这两个包是好像是会报错的,不是错误代码,大家根据提示百度一下怎么解决,导入成功后就可以直接跑起来了

package com.yunduan.test;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Test {

	public static void main(String[] args) {
		Test test = new Test();
		try {
			test.synthesisImage();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void synthesisImage() throws Exception {
		String path = "C:/Users/wilson/Desktop/image/";
		File file1 = new File(path + "1.jpg");
		File file2 = new File(path + "2.jpg");
		File file3 = new File(path + "3.jpg");
		File file4 = new File(path + "4.jpg");
		BufferedImage read1 = javax.imageio.ImageIO.read(file1);
		BufferedImage read2 = javax.imageio.ImageIO.read(file2);
		BufferedImage read3 = javax.imageio.ImageIO.read(file3);
		BufferedImage read4 = javax.imageio.ImageIO.read(file4);
		// 获取图片的宽度
		int width1 = read1.getWidth();
		int width2 = read2.getWidth();
		int width3 = read3.getWidth();
		int width4 = read4.getWidth();
		// 获取图片高度
		int height1 = read1.getHeight();
		int height2 = read2.getHeight();
		int height3 = read3.getHeight();
		int height4 = read4.getHeight();
		// 定义一个buffer,宽度定为第一张图片的宽度,高度相加
		BufferedImage bufferedImage = new BufferedImage(width1, height1 + height2 + height3 + height4,
				BufferedImage.TYPE_INT_RGB);
		// 输出流
		FileOutputStream fileOutputStream = new FileOutputStream("C:/Users/wilson/Desktop/image/big.jpg");
		// 合成图片
		Graphics image = bufferedImage.createGraphics();
		// 参数1 (要添加的图片) 参数2(开始的x轴坐标) 参数3(添加 图片的y轴坐标)
		// 参数4 (要添加的图片宽度) 参数 5(要添加的图片高度)
		image.drawImage(read1, 0, 0, width1, height1, null);
		image.drawImage(read2, 0, height1, width2, height2, null);
		image.drawImage(read3, 0, height1 + height2, width3, height3, null);
		image.drawImage(read4, 0, height1 + height2 + height3, width4, height4, null);
		// 释放资源
		image.dispose();
		// 把合成图片生成至输出流
		JPEGImageEncoder createJPEGEncoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
		createJPEGEncoder.encode(bufferedImage);
		// 关闭输出流
		fileOutputStream.close();
		System.out.println("图片合成成功");
	}
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值