原图(工程所在目录7098849.jpg):
头像(工程所在目录20181023201750.jpg):
开始合成(执行如下main方法):
public static void main(String[] args) throws IOException { String rootPath = System.getProperty("user.dir"); String imageUrl = rootPath + File.separator + "7098849.jpg"; String headUrl = rootPath + File.separator + "20181023201750.jpg"; String newImageUrl = rootPath + File.separator + "20181023.jpg"; composePic(newImageUrl,imageUrl,headUrl); }
/** * 合成照片 * * @author wulinfeng * @param newImageUrl * @param imageUrl * @param headUrl */ private static void composePic(String newImageUrl, String imageUrl, String headUrl) { String nickName = "不想下火车的人"; // 昵称 String color = "230,206,145"; // 昵称颜色 String font = "思源黑体 CN Normal,1,34"; // 昵称字体 String pos = "156,70"; // 昵称位置 String headimg_pos = "40,40"; // 头像位置 String headimg_size = "88,88"; // 头像大小 BufferedImage srcImg = null; BufferedImage headImg = null; try { srcImg = ImageIO.read(new File(imageUrl)); headImg = ImageIO.read(new File(headUrl)); } catch (IOException e) { e.printStackTrace(); } if (srcImg == null || headImg == null) { return; } Graphics2D g = srcImg.createGraphics(); String[] colorArray = color.split(","); g.setColor(new Color(Integer.parseInt(colorArray[0]), Integer.parseInt(colorArray[1]), Integer.parseInt(colorArray[2]))); String[] fontArray = font.split(","); g.setFont(new Font(fontArray[0], Integer.parseInt(fontArray[1]), Integer.parseInt(fontArray[2]))); String[] posArray = pos.split(","); g.drawString(nickName, Integer.parseInt(posArray[0]), Integer.parseInt(posArray[1])); String[] headposArray = headimg_pos.split(","); String[] headsizeArray = headimg_size.split(","); g.drawImage(headImg, Integer.parseInt(headposArray[0]), Integer.parseInt(headposArray[1]), Integer.parseInt(headsizeArray[0]), Integer.parseInt(headsizeArray[1]), null); g.dispose(); try { FileOutputStream outImgStream = new FileOutputStream(newImageUrl); ImageIO.write(srcImg, "jpg", outImgStream); outImgStream.flush(); outImgStream.close(); } catch (IOException e) { e.printStackTrace(); } }
合成结果(工程所在目录20181023.jpg):