代码说话
package com.example.demo.image;
import sun.misc.BASE64Decoder;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.List;
public class PicImageTest {
public static void main(String[] args) throws Exception{
List<File> files = new ArrayList<>();
File file1 = new File("D:/1.jpg");
File file2 = new File("D:/11.jpg");
files.add(file1);
files.add(file2);
String path = "D:/222.jpg";
mergeHorizontal(files, path);
}
//竖向合成
public static void mergeVertical(List<File> files, String path){
try {
Integer allWidth = 0; //计算画布总宽
Integer allHeight = 0; //计算画布总高
List<BufferedImage> imgs = new ArrayList<>();
for(int i=0; i<files.size(); i++){
imgs.add(ImageIO.read(files.get(i)));
//因为是竖向合成,拿图片里最大的一个宽度就行
allWidth = Math.max(allWidth,imgs.get(i).getWidth());
allHeight += imgs.get(i).getHeight();
}
BufferedImage combined = new BufferedImage(allWidth, allHeight,BufferedImage.TYPE_INT_RGB);
Graphics g = combined.getGraphics();
//设置画布背景颜色 ,默认黑色
g.setColor(Color.white);
g.fillRect(0, 0, allWidth, allHeight);
Integer height = 0;
for(int i=0; i< imgs.size(); i++){
g.drawImage(imgs.get(i), 0, height,null);
//+10为了设置上下两个图片间距
height += imgs.get(i).getHeight()+10;
}
ImageIO.write(combined, "jpg", new File(path));
System.out.println("===合成成功====");
} catch (Exception e) {
System.out.println("===合成失败====");
e.printStackTrace();
}
}
//横向合成
public static void mergeHorizontal(List<File> files, String path){
try {
Integer allWidth = 0;
Integer allHeight = 0;
List<BufferedImage> imgs = new ArrayList<>();
for(int i=0; i<files.size(); i++){
imgs.add(ImageIO.read(files.get(i)));
allHeight = Math.max(allHeight,imgs.get(i).getHeight());
allWidth += imgs.get(i).getWidth();
}
BufferedImage combined = new BufferedImage(allWidth, allHeight, BufferedImage.TYPE_INT_RGB);
Graphics g = combined.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, allWidth, allHeight);
Integer width = 0;
for(int i=0; i< imgs.size(); i++){
g.drawImage(imgs.get(i), width, 0, null);
//设置横向间距
width += imgs.get(i).getWidth()+10;
}
ImageIO.write(combined, "jpg", new File(path));
System.out.println("===合成成功====");
} catch (Exception e) {
System.out.println("===合成失败====");
e.printStackTrace();
}
}
//字符串类型图片转换
public static BufferedImage base64StringToImg(String base64String) {
try {
byte[] bytes = Base64.getDecoder().decode(data);
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
return ImageIO.read(in);
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
}