1,背景
某一张小尺寸图片需要覆盖在另一张大图片的某处
2,流程
/**
* @param img1 待合并的第一张图
* @param img2 带合并的第二张图
* @return 返回合并后的BufferedImage对象
*/
private static BufferedImage mergeImg(BufferedImage img1, BufferedImage img2) {
int w1 = img1.getWidth();
int h1 = img1.getHeight();
int h2 = img2.getHeight();
int w2 = img2.getWidth();
Graphics2D graphics2D = null;
// 生成新图片
BufferedImage destImage = null;
destImage = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_RGB);
graphics2D = destImage.createGraphics();
//插入的位置坐标需要手动尝试
graphics2D.drawImage(img1, 0, 0, w1, h1, null);
graphics2D.drawImage(img2, 0, 0, w2, h2, null);
graphics2D.dispose();
return destImage;
}
/**
* 生成新图片到本地
*/
public static void writeImageLocal(String newImage, BufferedImage img) {
if (newImage != null && img != null) {
try {
File outputfile = new File(newImage);
ImageIO.write(img, "jpg", outputfile);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) throws Exception {
InputStream is1 = new FileInputStream("/Users/XXX/Desktop/picture1.png");
InputStream is2 = new FileInputStream("/Users/XXXDesktop/picture2.png");
BufferedImage readImg1 = ImageIO.read(is1);
BufferedImage readImg2 = ImageIO.read(is2);
BufferedImage mergeImg = mergeImg(readImg1, readImg2);
writeImageLocal("/Users/XXX/Desktop/2.png", mergeImg);
}
3,结果
素材1、2:
结果:(坐标需手动尝试)