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("图片合成成功");
}
}